What is ftell in C?
ftell in C is used to determine the current position of the pointer to the FILE object with respect to the start of the file.
The function declaration in the standard C library is as follows:
long ftell(FILE *stream)
Parameters
stream: Pointer to the FILE object
Return value
On Success: Current position value of the file pointer with respect to the start of the file
On Failure: -1L returned, and global variable errno is set to a system-defined positive value
Example program
Below is a C program that uses ftell to output the file pointer position after each word in the string “I love reading Edpresso shots.” stored in file.txt:
#include <stdio.h>int main (){/*Opening file in read mode */FILE *fp = fopen("file.txt","r");char word1[10], word2[10], word3[10], word4[10], word5[10];/*First word stored in the string and pointer moves beyond first word */fscanf(fp,"%s", word1);printf("Word: %s \t", word1);printf("Pointer position: %ld \n", ftell(fp));/*Second word stored in the string and pointer moves beyond the second word */fscanf(fp,"%s", word2);printf("Word: %s \t", word2);printf("Pointer position: %ld \n", ftell(fp));/* Same process for these words as well */fscanf(fp,"%s", word3);printf("Word: %s \t", word3);printf("Pointer position: %ld \n", ftell(fp));fscanf(fp,"%s", word4);printf("Word: %s \t", word4);printf("Pointer position: %ld \n", ftell(fp));fscanf(fp,"%s \t", word5);printf("Word: %s \t", word5);printf("Pointer position: %ld \n", ftell(fp));return 0;}
Explanation
In the above program, we use fscanf to read each word and store them in a variable, and move the file pointer to the space before the next word. ftell(fp) then finds the position of the file pointer from the start of the file. For example in line 17, the file pointer moves to the space after the substring “I love” and therefore ftell outputs 6. Try and verify other outputs yourself.
Free Resources