In this tutorial we will see what is ftell function,why it’s used and how to use function with example.
ftell function :-. ftell() function is used to get the current position of the pointer in the file.
why ftell function is used ?
to get the current position of pointer in file.
ftell syntax in c
long ftell(FILE *fp);
1.In above syntax we can see that ftell() function has one parameter which is file pointer which points to file that holds location and mode of file.
2.ftell returns the current location of file pointer which is long type.
Consider file with content technical seek and we use ftell() function to get current position of pointer in file
At start when file opened.
=> This return 1 integer value as it pointing to start
Using fscanf () we read first string i.e technical
=> Now ftell returns 10 as ,first string read technical and now pointing to next
Program to demonstrate ftell function in c
FILE *fp ;
printf ("opening file in read mode");
fp=fopen("technical.txt","r"); //opening file in read mode
printf("\nread first string from file");
fscanf(fp,"%s",&string);. //reading first string
printf ("\n first string in file =%s,"string);
printf("\n current position in file=");
printf("%ld", ftell(fp));. //printing current position in file
- In above program we get current position in file using ftell() function.
- First we open file in read mode .
- Let us assume file technical.txt exist at current directory with content (content :- technical seek)
- First we read first string from file which is technical using the fscanf function (fscanf function which is used to read string from file)
- Now we get current position in file using ftell function (ftell(fp)) which returns the current position i.e 10
- Close the file.
opening file in read mode
reading first string from file
first string in file= technical
current position in file=10