System Calls for File Management

System Calls for File Management

Many system calls relate to the file system. In this section we will look at calls that operate on individual files; in the next one we will study those that involve directories or the file system as a whole.

To read or write a file, the file must first be opened using open. This call specifies the file name to be opened, either as an complete path name or relative to the working directory, and a code of O_RDONLY, O_WRONLY, or O_RDWR, meaning open for reading, writing, or both. To create a new file, the O_CREAT parameter is used. The file descriptor returned can then be used for reading or writing.  Afterward, the file can be closed by close, which makes the file descriptor available for reuse on a subsequent open. The most heavily used calls are certainly read and write. We saw read earlier. Write has the same features.

Although the majority of programs read and write files in sequence, for some applications programs need to be able to access any part of a file at  random. Connected with each file is a pointer that indicates the current position in the file. When reading (writing) in sequence, it usually points to the next byte to be read (written). The lseek call changes the value of the position pointer, so that subsequent calls to read or write can begin anywhere in the file.

Lseek has three parameters: the first is the file descriptor for the file, the second is a file position, and the third tells whether the file position is relative to the beginning of the file, the current position, or the end of the file. The value returned by lseek is the absolute  position in the file (in bytes) after changing the pointer.

For each file, UNIX keeps track of the file mode (regular file, special file, directory, and so on), size, time of last modification, and other  information. Programs can ask to see this information via the stat system call. The first parameter specifies the file to be inspected; the second one is a pointer to a structure where the information is to be put. The fstat calls does the same thing for an open file.


system calls, file system, unix