The Pointer The Pointer - 1 month ago 5
C Question

How do functions like fscanf() and fgets() remember where in the file to start reading from?

For instance, when reading a file using

, it seems to remember where it last left terminated, rather than starting from the beginning of the file again. Can someone please elaborate on how exactly this works? I've finding it difficult to use these functions, since I do not understand this component.


The FILE * parameter points to a buffer and a file handle (see the fileno() function).

The actual where is remembered in the kernel in the file structure.

There is a legend that the FILE * pointer points into the file. This is not literally true, but it might as well be true for the interpretation of the beginning programmer.

In fact what happens is as follows: Every process has an array in kernel of type struct file (this type is not defined in userspace so don't go looking for it) that contains all of its open files. A handle is returned by the open() syscall that is merely an index into the array. The function fileno() retrieves the handle from the FILE * pointer returned by fopen() and can be manipulated directly. This is usually a bad idea except for accessing ioctl() or fctl() as you will end up fighting with the internal buffer in the FILE object.

One of the members of struct file is loff_t f_pos which is the exact location in bytes the kernel read() or write() stopped at. This is buffered in FILE which knows how many bytes it read ahead or pended for a later write for you.