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

Getting current position with ftell

Getting current position with ftell

What you'll learn: How to use the ftell function to determine your exact byte location within a file.

The Digital Bookmark

Imagine you are reading a massive 800-page novel. If you need to step away, you don't just close the book; you use a bookmark or remember the page number so you can return to that exact spot later.

In C, when you open a file, the system maintains a "file position indicator." This is essentially a blinking cursor that moves forward every time you read or write a character. The ftell function acts as your digital bookmark. It asks the system: "At which byte offset from the beginning of the file is the cursor currently sitting?"

Using ftell

The ftell function is straightforward. It takes one argument—your file pointer—and returns a long integer representing the number of bytes from the start of the file. If you are at the very beginning, it returns 0.

Here is how you might use it in a program:

#include <stdio.h>

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

    // Read the first 5 characters
    char buffer[6];
    fgets(buffer, 6, fptr);
    
    // Where are we now?
    long position = ftell(fptr);
    
    printf("After reading 5 bytes, the cursor is at position: %ld\n", position);

    fclose(fptr);
    return 0;
}

Why is this useful?

You might wonder why you need to ask where you are if you're the one doing the reading. However, ftell is powerful when combined with other seeking functions.

Common use cases include:

  1. Measuring File Size: By seeking to the very end of a file and calling ftell, you can instantly find out exactly how many bytes the file contains.
  2. Saving State: If you are processing a massive data file and need to pause, you can save the ftell value to a variable or a config file, then resume from that exact byte later.
  3. Complex Parsing: When reading files with complex headers, you might need to jump ahead to check a value and then jump back to your original "bookmarked" position.

Remember that ftell returns a long, so always use the %ld format specifier when printing it to the console.

Key takeaway

The ftell function returns the current byte offset of the file pointer, allowing you to track or save your progress within a file.