Course contentsShow
← C
Lesson 738 of 1,21910. Input and OutputFree lesson

Using fgetpos and fsetpos for large files

Using fgetpos and fsetpos for large files

What you'll learn: How to handle file positions using a specialized data type that works even for massive files where standard integers might fail.

Previously, you likely used ftell and fseek. These functions use a long integer to track where you are in a file. While a long is usually 32 or 64 bits, on many systems, it has a limit. If you are dealing with a "Big Data" file that is several gigabytes or terabytes in size, a standard integer might not be large enough to represent the byte count. This is where fgetpos and fsetpos come in.

The "Bookmark" Analogy

Think of fseek like counting every single character in a book from the beginning to find your page. If the book is millions of pages long, you eventually run out of numbers you can easily hold in your head.

fgetpos and fsetpos work differently. Instead of giving you a raw number, fgetpos hands you a "physical bookmark" (an object of type fpos_t). You don't necessarily need to know what’s written on the bookmark; you just hand it back to the computer later using fsetpos, and the computer instantly flips to that exact spot.

How to use fpos_t

The key here is the fpos_t type. It is a complex type defined by your system specifically to store file positions, no matter how large the file is.

#include <stdio.h>

int main() {
    FILE *file = fopen("huge_data.bin", "rb");
    if (file == NULL) return 1;

    fpos_t bookmark;

    // Move somewhere in the file
    fseek(file, 100, SEEK_SET);

    // Record the current position into our bookmark
    if (fgetpos(file, &bookmark) != 0) {
        perror("Error getting position");
    }

    // Read some data or move elsewhere
    fseek(file, 5000, SEEK_CUR);

    // Now, jump back to exactly where we were
    if (fsetpos(file, &bookmark) != 0) {
        perror("Error setting position");
    }

    fclose(file);
    return 0;
}

Why use this?

  1. Portability: Different operating systems handle giant files differently. fpos_t hides those details from you.
  2. Safety: It prevents "integer overflow" errors that happen when a file size exceeds the maximum value a long can hold.
  3. Future-proofing: Even if files get even larger in the future, your code using fpos_t will likely still work because the compiler manages the underlying data size.

Key takeaway

Use fgetpos and fsetpos with the fpos_t type to reliably "bookmark" and return to locations in files of any size.