C Programming - Beginner to Brilliance / File Handling in C

File Pointers and fseek, ftell

๐Ÿ“Œ What is a File Pointer?

In C, whenever we open a file using fopen(), we get back a file pointer โ€” an internal handler used to track the current position in the file.

FILE *fp = fopen("myfile.txt", "r");
  • This fp points to the beginning of the file when it's opened in read mode.

  • As you read or write, the pointer moves automatically.

Think of it like a cursor in a text editor:

  • It starts at the top,

  • moves with each character/line read or written,

  • and you can manually move it using special functions.


๐Ÿ” Why do we need to control the file pointer?

  • ๐Ÿ” Reread a specific part of the file

  • โฉ Skip unnecessary data

  • ๐Ÿ“ฆ Append new data at specific positions

  • ๐Ÿ” Jump to a specific record in a binary file

  • ๐Ÿ”„ Reset file pointer to reprocess content


๐Ÿ“š fseek() โ€“ Move the File Pointer

fseek() is used to manually move the file pointer to a specific location within a file. This is especially useful when you want to skip over certain parts of the file or jump directly to a known position for reading or writing. It provides flexibility for random access instead of just sequential reading or writing.

๐Ÿ”ง Syntax:

int fseek(FILE *fp, long offset, int origin);

๐Ÿ“Œ Parameter

๐Ÿ“˜ Description

fp

File pointer

offset

Number of bytes to move (positive or negative)

origin

Reference point for movement

๐ŸŽฏ Values for origin:

๐Ÿ”น Macro

๐Ÿ“ Meaning

SEEK_SET

Beginning of file

SEEK_CUR

Current position

SEEK_END

End of file


โœ… Example 1: Move to the 10th byte from start

fseek(fp, 10, SEEK_SET);  // Moves pointer to byte 10 (zero-based)

โœ… Example 2: Move 5 bytes forward from current

fseek(fp, 5, SEEK_CUR);

โœ… Example 3: Go 20 bytes before the end

fseek(fp, -20, SEEK_END);

โš ๏ธ Notes:

  • fseek() returns 0 on success and non-zero on failure.

  • offset is in bytes, so it's exact, unlike skipping characters or lines.


๐Ÿ“ ftell() โ€“ Get Current Position of File Pointer

ftell() returns the current position of the file pointer, measured in bytes from the beginning of the file. It's helpful when you need to know where you are in the fileโ€”such as for tracking progress or for returning to that location later.

๐Ÿ”ง Syntax:

long position = ftell(fp);
  • Returns the current byte offset from the beginning of the file.

  • Very useful for:

    • Logging position

    • Creating bookmarks in files

    • Debugging or offset calculations


โœ… Example:

FILE *fp = fopen("sample.txt", "r");
fseek(fp, 15, SEEK_SET);
long pos = ftell(fp);
printf("Current position: %ld\\n", pos);  // Output: 15

๐Ÿ”„ rewind() โ€“ Reset Pointer to Beginning

rewind(fp);  // Equivalent to fseek(fp, 0, SEEK_SET);
  • Doesnโ€™t return any value

  • Resets error and EOF flags too


๐Ÿ“„ Complete Example โ€“ Using fseek(), ftell(), and rewind()

๐Ÿ“„ Content of demo.txt

Welcome to CodeVeda!

Each character (including spaces) is 1 byte.

Position 10 โ†’ "Welcome to " โ†’ the 11th character is 'C'.

#include <stdio.h>

int main() {
    // Open the file in read mode
    FILE *fp = fopen("demo.txt", "r");
    if (fp == NULL) {
        printf("File error.\\n");
        return 1;
    }

    // Move the file pointer to the 10th byte from the beginning
    fseek(fp, 10, SEEK_SET);                    // 'C' of "CodeVeda"
    printf("Position after fseek: %ld\\n", ftell(fp)); // Should print 10

    // Read the character at the 10th byte position
    char ch = fgetc(fp);
    printf("Character at position 10: %c\\n", ch);  // Should print 'C'

    // Rewind resets the file pointer back to the beginning
    rewind(fp);
    printf("Position after rewind: %ld\\n", ftell(fp));        // Should print 0

    fclose(fp);                                              // Close the file
    return 0;
}

โ— Common Mistakes to Avoid

โš ๏ธ Mistake

๐Ÿ” Why it matters

Not checking return value of fseek()

It may silently fail if file is too small

Using ftell() on a closed file

Causes undefined behavior

Misusing offset in binary vs. text mode

Especially on Windows, due to newline encoding differences

Assuming fseek() always works in text mode

It may not behave as expected due to newline translation


๐Ÿ“Œ Use Cases of File Pointer Manipulation

  • ๐Ÿ“œ Reading a specific record in a fixed-size database file

  • ๐Ÿ”„ Resetting file to beginning without reopening

  • ๐Ÿงฎ Finding file size:

๐Ÿ“„ Content of textfile.txt

Name: CodeVeda
Age: 25
This is a simple line.

โœ… Code:

#include <stdio.h>

int main() {
    FILE *fp = fopen("textfile.txt", "r");
    if (fp == NULL) {
        printf("Error opening file.\\n");
        return 1;
    }

    fseek(fp, 0, SEEK_END);     // Move to end of file
    long size = ftell(fp);      // Get the current file position (size in bytes)
    rewind(fp);                 // Go back to beginning of file

    printf("File size: %ld bytes\\n", size);
    fclose(fp);
    return 0;
}
File size: 50 bytes