The GNU C Library: File Position

Previous: , Up: I/O Concepts   [Contents][Index]


11.1.2 File Position

One of the attributes of an open file is its file position that keeps track of where in the file the next character is to be read or written. On GNU systems, and all POSIX.1 systems, the file position is simply an integer representing the number of bytes from the beginning of the file.

The file position is normally set to the beginning of the file when it is opened, and each time a character is read or written, the file position is incremented. In other words, access to the file is normally sequential.

Ordinary files permit read or write operations at any position within the file. Some other kinds of files may also permit this. Files which do permit this are sometimes referred to as random-access files. You can change the file position using the fseek function on a stream (see File Positioning) or the lseek function on a file descriptor (see I/O Primitives). If you try to change the file position on a file that doesn’t support random access, you get the ESPIPE error.

Streams and descriptors that are opened for append access are treated specially for output: output to such files is always appended sequentially to the end of the file, regardless of the file position. However, the file position is still used to control where in the file reading is done.

If you think about it, you’ll realize that several programs can read a given file at the same time. In order for each program to be able to read the file at its own pace, each program must have its own file pointer, which is not affected by anything the other programs do.

In fact, each opening of a file creates a separate file position. Thus, if you open a file twice even in the same program, you get two streams or descriptors with independent file positions.

By contrast, if you open a descriptor and then duplicate it to get another descriptor, these two descriptors share the same file position: changing the file position of one descriptor will affect the other.


Previous: , Up: I/O Concepts   [Contents][Index]