ftell() in C Programming With Example
Hello Everyone, In this article, we will discuss about function ftell() in C Programming. This functions is used to determine the current position of the file pointer in a file. Understanding how to use ftell() can help you manage file operations more effectively, making it easier to read from or write to specific parts of a file. Whether you are new to C or have some experience, this guide will help you to understand basics of ftell() in C effectively with examples. Let’s get started.
What is ftell() in C
ftell
is a standard library function in C programming language used to determine the current position of the file pointer in a given file. The function returns the current offset from the beginning of the file in bytes. It is part of the stdio.h
library and takes a FILE
pointer as an argument.
Syntax of ftell() in C
long int ftell(FILE *stream);
Where:
stream
– the pointer to the file stream to be queried
The return value of ftell is the current file position in bytes from the beginning of the file, or -1L if an error occurs.
Example:
#include <stdio.h>
int main()
{
FILE *fp;
long int pos;
fp = fopen("example.txt", "r");
if (fp == NULL) {
perror("Error opening file");
return -1;
}
fseek(fp, 0L, SEEK_END); // move to the end of the file
pos = ftell(fp); // get the current position (end of the file)
printf("The file size is %ld bytes.\\n", pos);
fclose(fp);
return 0;
}
In this example, the program opens the file “example.txt” in read mode using the fopen function. The program then uses fseek to move the file pointer to the end of the file, and then uses ftell to get the current position of the file pointer. The position is then printed to the console as the size of the file. Finally, the program closes the file using fclose.