Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

How do C functions like fscanf() and fgets() remember where in the file to start reading from? For instance, when reading a file using fscanf(), it seems to remember where it last left terminated, rather than starting from the beginning of the file again. How exactly does this work?

like image 262
The Pointer Avatar asked Sep 21 '16 01:09

The Pointer


1 Answers

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.

like image 97
Joshua Avatar answered Oct 16 '22 21:10

Joshua