Adventures in Random Access: fseek() and ftell()
The fseek() function enables you to treat a file like an array and move directly to any particular byte in a file opened by fopen(). To see how it works, let's create a program (see Listing 12.5) that displays a file in reverse order. Borrowing from the earlier examples, it uses a command-line argument to get the name of the file it will read. Note that fseek() has three arguments and returns an int value. The ftell() function returns the current position in a file as a long value.
Listing 12.5 The reverse.c program.
/* reverse.c -- displays a file in reverse order */ #include <stdio.h> #include <stdlib.h> #define CNTL_Z '\032' /* eof marker in DOS text files */ #define SLEN 50 int main(void) ... |
Get C Primer Plus®, Third Edition 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.