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 (Listing 13.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 13.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) { char ...

Get C Primer Plus, Fourth 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.