C++ ftell()

The ftell() function in C++ returns the current position of the file pointer.

ftell() prototype

long ftell(FILE* stream);

The ftell() function takes a file stream as its argument and returns the current value of the file position indicator for the given stream as a long int type.

It is defined in <cstdio> header file.

ftell() Parameters

stream: The file stream whose current position is returned.

ftell() Return value

On success, the ftell() function returns the file position indicator. Otherwise, it returns -1L.

Example: How ftell() function works

#include <iostream>
#include <cstdio>

using namespace std;

int main()
    int pos;
    char c;
    FILE *fp;
    fp = fopen("file.txt", "r");
    if (fp)
        while ((c = getc(fp)) != EOF)
            pos = ftell(fp);
            cout << "At position " << pos << ", character is " << c << endl;
        perror("Error reading file");
    return 0;

When you run the program, the output will be:

At position 1, character is P
At position 2, character is r
At position 3, character is o
At position 4, character is g
At position 5, character is r
At position 6, character is a
At position 7, character is m
At position 8, character is i
At position 9, character is z
At position 10, character is .
At position 11, character is c
At position 12, character is o
At position 13, character is m
Did you find this article helpful?