0
0
CHow-ToBeginner · 3 min read

How to Use ftell in C: Syntax, Example, and Tips

In C, use ftell(FILE *stream) to get the current position of the file pointer in bytes from the beginning of the file. It returns a long value indicating this position or -1L if an error occurs.
📐

Syntax

The ftell function returns the current position of the file pointer in a file stream. It takes one argument:

  • FILE *stream: A pointer to a file object that identifies the stream.

The return value is a long integer representing the byte offset from the beginning of the file. If an error occurs, it returns -1L.

c
long ftell(FILE *stream);
💻

Example

This example opens a text file, moves the file pointer using fseek, then uses ftell to find the current position in the file.

c
#include <stdio.h>

int main() {
    FILE *file = fopen("example.txt", "r");
    if (file == NULL) {
        perror("Failed to open file");
        return 1;
    }

    // Move file pointer 10 bytes from the start
    if (fseek(file, 10, SEEK_SET) != 0) {
        perror("fseek failed");
        fclose(file);
        return 1;
    }

    // Get current position
    long pos = ftell(file);
    if (pos == -1L) {
        perror("ftell error");
        fclose(file);
        return 1;
    }

    printf("Current file position: %ld\n", pos);

    fclose(file);
    return 0;
}
Output
Current file position: 10
⚠️

Common Pitfalls

  • Calling ftell on a file opened in text mode may give unexpected results on some systems because of newline translations.
  • Always check if ftell returns -1L to detect errors.
  • Do not use ftell on streams that are not seekable (like pipes or sockets).
  • Remember to open the file before calling ftell and close it afterward.
c
#include <stdio.h>

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

    // Wrong: Not checking ftell return value
    long pos = ftell(file);
    // pos might be -1L on error, but we ignore it

    // Correct: Check ftell return value
    if (pos == -1L) {
        perror("ftell failed");
    } else {
        printf("Position: %ld\n", pos);
    }

    fclose(file);
    return 0;
}
📊

Quick Reference

ftell Cheat Sheet:

FunctionPurposeReturns
ftell(FILE *stream)Get current file pointer positionPosition as long or -1L on error
fseek(FILE *stream, long offset, int whence)Move file pointer0 on success, non-zero on error
FunctionPurposeReturns
ftell(FILE *stream)Get current file pointer positionPosition as long or -1L on error
fseek(FILE *stream, long offset, int whence)Move file pointer0 on success, non-zero on error

Key Takeaways

Use ftell to find the current byte position of the file pointer in a file stream.
Always check if ftell returns -1L to handle errors properly.
ftell works best with binary files or files opened in binary mode for accurate positions.
Do not use ftell on non-seekable streams like pipes or sockets.
Combine ftell with fseek to navigate and track positions in files.