Seeking through the Stream

Just as the lseek() system call can be used to set the file pointer in preparation for a subsequent read or write, the fseek() library function can be called to set the file pointer for the stream such that the next read or write will start from that offset.

#include <stdio.h>

int fseek(FILE *stream, long int offset, int whence);

The offset and whence arguments are identical to those supported by the lseek() system call. The following example shows the effect of calling fseek() on the file stream:

1 #include <stdio.h>
2
3 main()
4 {
5          FILE        *fp;
6          char        c;
7
8          fp = fopen(“infile”, “r”);
9          printf(“address of fp     = 0x%x\n”, fp);
10         printf(“ fp->_IO_buf_base = 0x%x\n”, fp->_IO_buf_base);
11         printf(“ fp->_IO_read_ptr = 0x%x\n”, fp->_IO_read_ptr);
12
13         c = getc(fp);
14         printf(“ fp->_IO_read_ptr = 0x%x\n”, fp->_IO_read_ptr);
15         fseek(fp, 8192, SEEK_SET);
16         printf(“ fp->_IO_read_ptr = 0x%x\n”, fp->_IO_read_ptr);
17         c = getc(fp);
18         printf(“ fp->_IO_read_ptr = 0x%x\n”, fp->_IO_read_ptr);
19 }

By calling getc(), a 4KB read is used to fill up the buffer pointed to by _IO_buf_base. Because only a single character is returned by getc(), the read pointer is only advanced by one. The call to fseek() modifies the read pointer as shown below:

$ fpseek
Address of fp    = 0x80497e0
fp->_IO_buf_base = 0x0
fp->_IO_read_ptr = 0x0
fp->_IO_read_ptr = 0x40019001
fp->_IO_read_ptr = 0x40019000
fp->_IO_read_ptr = 0x40019001

Note that no data needs to be read for the second call ...

Get UNIX Filesystems: Evolution, Design, and Implementation now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.