ftell in c – ftell C Library Function

ftell in c: The function long int ftell(FILE *stream); returns the current position of the given stream. It gets the current position from the position indicator of the stream.

Function prototype of ftell

long int ftell(FILE *stream);
  • stream : A pointer to a FILE object which identifies a stream.

Return value of ftell

This function returns the current value of the position indicator on success. In case of error, it returns -1L and sets the global variable errno to a system-specific positive value.

C program using ftell function

The following program shows the use of ftell function to get the current position of a stream. It traverse the file from beginning till end and prints the position of every character in file.

ftell C Library Function 1

#include <stdio.h>
 
int main(){
   FILE *file;
   int c, position;
   
   file = fopen("textFile.txt","w+");
   if(file == NULL){
      perror("Error: Unable to open a file");
   } else {
       fputs("BTechgeeks.com", file);
       fseek(file, 0, SEEK_SET);
       /* Printing characters and their positions in file */
       while(!feof(file)){
          c = fgetc(file);
          printf("%c is at position %d\n", c, ftell(file));
       }
       fclose(file);
   }
    
   return(0);
}

Output

T is at position 1
e is at position 2
c is at position 3
H is at position 4
C is at position 5
r is at position 6
a is at position 7
s is at position 8
H is at position 9
C is at position 10
o is at position 11
u is at position 12
r is at position 13
s is at position 14
e is at position 15
. is at position 16
c is at position 17
o is at position 18
m is at position 19