C ftell()
Function
Syntax
long ftell(FILE *stream);
Example
#include <stdio.h>
int main()
{
FILE *fptr = fopen("example.txt", "r");
if (fptr == NULL) {
printf("Error opening file!");
return 1;
}
fseek(fptr, 0, SEEK_END); // move pointer to end of file
long size = ftell(fptr); // get the position of pointer
fclose(fptr); // close the file
printf("Size of the file is %ld bytes.\n", size);
return 0;
}
Output
If the example.txt
file has 100 characters, the output of the above program will be:
Size of the file is 100 bytes.
Explanation
The ftell()
function is used to determine the current position of the file pointer in a file. It takes a FILE
pointer as an argument and returns the current position of the file pointer as a long
integer value. The return value is the number of bytes from the beginning of the file.
Use
The ftell()
function is useful in situations where you need to determine the size of a file, or the position of the file pointer within a file. It is commonly used along with the fseek()
function to set the file pointer to a specific position within a file.
Important Points
- The
ftell()
function is used to determine the current position of a file pointer in a file. - The return value of
ftell()
is along
integer representing the current position of the file pointer in bytes from the beginning of the file. - The
ftell()
function is commonly used along with thefseek()
function to set the file pointer to a specific position within a file. - The
ftell()
function is only applicable for binary files so it can't be used for text files.
Summary
The ftell()
function is a C standard library function that returns the current position of the file pointer. It is used to determine the size of a file or the position of the file pointer within a file. It is commonly used with the fseek()
function to set the file pointer to a specific position within a file. Understanding the basic syntax and use cases for this function can be beneficial in file handling operations.