Example of ftell()
The file taken contains the following data:
“Yesterday was history, tomorrow is a mystery, but today is a gift, which is why we call it the present.” (without the quotes)
C
#include <stdio.h>
int main()
{
/* Opening file in the read mode */
FILE *fp = fopen("file.txt", "r");
/* Reading the first string */
char string[25];
fscanf(fp,"%s", string);
printf("%ld \n", ftell(fp));
/* Using SEEK_END constant to move the file pointer to the end of file. */
fseek(fp, 0, SEEK_END);
int length = ftell(fp);
printf("Size of file: %d bytes", length);
return 0;
}

You can also try this code with Online C Compiler
Run Code
Output:
9
Size of file: 103 bytes
Explanation:
When the fscanf() statement is executed word “Yesterday” is stored in the string, and the pointer is moved beyond “Yesterday”. Therefore ftell(fp) returns 9 as the length of “someone” is 8.
We can also use the ftell() function to get the file size after moving the file pointer to the end of the file.
You can also read about dynamic array in c and Short int in C Programming
Frequently Asked Questions
What is file handling and its types?
File Handling is the process of storing data in a file with a program. In the C programming language, the programs keep results and other program data to a file using file handling. We can also extract/fetch data from a file to work with it in the program.
What is the importance of file handling in C?
Reusability: When a program is terminated, the data will get lost. You can store your data in a file; even if the program terminates, you will not lose your data.
Portability: You can quickly move the file's data from one computer to another without any changes.
What are file modes in C?
There are many modes for opening a file:
- r - open a file in reading mode.
- w - opens or creates a text file in write mode.
- a - opens a file in append mode.
- r+ - opens a file in both read and write mode.
- a+ - opens a file in both read and write mode.
- w+ - opens a file in both read and write mode.
How do I use ftell() function in C++?
The ftell() function in C++ takes a file stream as its argument and returns the current value of the file pointer indicator for the given stream as a long int type. It is defined in <cstdio> header file. You can use it like:
long ftell(FILE* stream);

You can also try this code with Online C++ Compiler
Run CodeConclusion
This article gives information about the ftell() function in the C programming language. We see how one can utilize the functionality the ftell() function provides and use it in their programs.
Also read,