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

The file position indicator

The file position indicator

What you'll learn: How C uses an internal "bookmark" to track where you are reading or writing inside a file.

The invisible bookmark

Imagine you are reading a long novel. You don't read every page simultaneously; instead, you use a bookmark to keep track of your progress. When you read a paragraph, you move the bookmark forward. When you want to go back to an earlier chapter, you physically move that bookmark to a previous page.

In C, every open file has a similar mechanism called the file position indicator. It is an invisible pointer managed by the operating system that points to the exact byte where the next read or write operation will occur.

How it moves automatically

Most of the time, you don't have to worry about the indicator because it moves automatically. When you open a file in "r" (read) mode, the indicator starts at the very beginning (offset 0). As you call functions like fgetc() or fgets(), the indicator slides forward by the number of bytes you just processed.

Think of it like a typewriter head: as you type a character, the head moves one space to the right, ready for the next letter.

Seeing the indicator in action

Even though we can't see the indicator visually, we can observe its behavior. If you read the first 10 bytes of a file, the indicator sits at position 10. If you call a read function again, it won't start from the beginning; it starts right where it left off at byte 10.

#include <stdio.h>

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

    // Read the first character
    char first = fgetc(fptr); 
    // The indicator is now at position 1

    // Read the second character
    char second = fgetc(fptr); 
    // The indicator is now at position 2

    printf("First: %c, Second: %c\n", first, second);

    fclose(fptr);
    return 0;
}

Why it matters

Understanding the position indicator is the foundation for "File Seeking." If you want to jump to the middle of a massive database file without reading everything that came before it, you must tell C to move this indicator manually. Without this bookmark, we would be forced to read every file linearly from start to finish, which would be incredibly slow and inefficient.

Key takeaway

The file position indicator is a hidden counter that tracks the current byte offset, advancing automatically every time you read or write data.