Introduction
- most file I/O on a UNIX system can be performed using only five functions:open,read,write,lseek and close
- the functions described in this chapter are often unbuffered I/O,,unbuffered means each read or write invokes a system call in the kernel.they are not part of ISO C,are part of POSIX.1 and the Single UNIX Specification.
file descriptors
- to the kernel,all open files are referred to by file descriptors,it is a non-negtive integer
- UNIX system shells associate file descriptor 0 with the standard input of a process and 1 with the standard output,2 with the standard err,but it is not a feature of the kernel,we can use STDIN_FILENE,STDOUT_FILENO,STDERR_FILENO to improve the readability which are defined in unistd.h
- file descriptors range from 0 to OPEN_MAX-1.
open and openat functions
- a file is opened or created by calling either the open function or the openat function.
filename and pathname truncation
- if the filename length over the NAME_MAX,some systems truncate the filename beyond the NAME_MAX character,some return an error status
close function
- close a file will release any record locks that the process may have on the file.
- when a process terminates,all of its open file will be closed automatically by the kernel
lseek function
- every open file has a associated “current file offset”,a non-negtive integer measures the number of bytes from the beginning of the file,read of write function often start at the current file offset and cause the offset to be increaed when reading or writing.
- an open file’s offset can be set explicitly by calling lseek.
- this technique can also be used to determine if a file is capable of seeking,if the file descriptor refers to a pipe,FIFO,or socket,lseek sets errno to ESPIPE and returns -1.
- for certain devices,the offset can be negtive
- the offset can be larger than the file size,in which case the next write to the file extend the file,any bytes in a file that have not been written are read back as 0.