Skip to Content
UNIX Filesystems: Evolution, Design, and Implementation
book

UNIX Filesystems: Evolution, Design, and Implementation

by Steve D. Pate
January 2003
Intermediate to advanced content levelIntermediate to advanced
480 pages
13h 22m
English
Wiley
Content preview from UNIX Filesystems: Evolution, Design, and Implementation

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Design and Implementation of the FreeBSD Operating System, 2nd Edition

Design and Implementation of the FreeBSD Operating System, 2nd Edition

Marshall Kirk McKusick, George V. Neville-Neil, Robert N.M. Watson

Publisher Resources

ISBN: 9780471456759Purchase book