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

Moving the pointer with fseek

Moving the pointer with fseek

What you'll learn: How to jump to any specific location inside a file without reading through it sequentially.

The Record Player Analogy

Imagine a file is like an old vinyl record. When you play music, the needle moves from the outer edge to the center, reading every groove in order. This is how we’ve handled files so far—reading line by line.

However, if you want to hear the third song, you don't listen to the first two; you lift the needle and drop it exactly where the third song begins. In C, fseek() is the tool that lets you lift the "file needle" (the position pointer) and place it anywhere you want.

Using fseek

The fseek() function requires three pieces of information: the file pointer, how many bytes to move (the offset), and a starting reference point.

There are three constants used for the reference point:

  1. SEEK_SET: The very beginning of the file.
  2. SEEK_CUR: The pointer's current position.
  3. SEEK_END: The very end of the file.

Code Example

Here is how you might jump to the 10th byte of a file to read a single character:

#include <stdio.h>

int main() {
    FILE *fptr = fopen("data.txt", "r");
    
    if (fptr == NULL) return 1;

    // Move the pointer 10 bytes from the start (SEEK_SET)
    // 0 is the first byte, so 10 is the 11th character
    fseek(fptr, 10, SEEK_SET);

    char ch = fgetc(fptr);
    printf("The character at position 10 is: %c\n", ch);

    fclose(fptr);
    return 0;
}

Why use it?

Seeking is essential for "Random Access." If you have a massive database file containing thousands of user profiles, and you know each profile is exactly 100 bytes long, you don't need to read the whole file to find user #50. You simply fseek to byte 5000 and start reading. It is significantly faster and more efficient than scanning the entire file from the top every time you need a specific piece of data.

Key takeaway

Use fseek() to instantly teleport the file pointer to a specific byte, allowing you to read or write data out of order.