C programming ftell stdio.h

In C programming the <stdio.h> ftell function get the current position of the file indicator,which can later be used again to set the file indicator to that position an access the characters.The declaration of the function is given below.

long int ftell(FILE *stream);

stream -The pointer to the file from which the file indicator is to be noted.

Return type
int -Returns the current value of the file position indicator for the stream.On failure,the ftell function returns −1L and stores an implementation-defined positive value in errno.

In binary stream ‘ftell’ returns the number of characters from the beginning of the file.In text stream the file indicator is some unspecified information usable by ‘fseek’ to set the indicator to the position returned by ‘ftell’ during it’s call.

To understand the code example given below consider a “text.txt” file with the content “0123456789abcdefghijkl“.

Code example

FILE *fp=fopen(“text.txt” , “r+”);
int val , count ;
long int pos ;

if (fp != NULL)
while ( (val=fgetc(fp)) != EOF) //read text.txt file
printf(“%c”, val);

if (count == 10)
pos=ftell( fp ); //get the 11th file indicator
 printf(“File cannot be opened”);

printf(“\npos=%d\n” , pos);

fseek(fp, pos , SEEK_SET); //set the file indicator to 11th character

//Read the 11th and remaining characters
while( (val = fgetc(fp)) !=EOF )
printf(“%c”, val);

fclose( fp );



The returned value is 10,which simply means the the file indicator will be set to the next character which is the 11th character,hence after calling ‘fseek’ reading starts from the 11th character.

*Side Note

To save the access position in a multibyte stream, use the ‘fgetpos( )’ function, which also saves the stream’s multibyte parsing state.

Related links

->C fseek stdio.h

->C fgetpos stdio.h