The ftell()
function in C is used to determine the current file position indicator for a given file stream. It returns the current position as a long integer representing the offset in bytes from the beginning of the file.
Here’s the syntax of the ftell()
function:
long int ftell(FILE *stream);
The ftell()
function takes a file stream pointer (FILE *stream
) as its argument and returns a long int
value representing the file position indicator. The stream
parameter is a pointer to a FILE
object, which is typically obtained by opening a file using the fopen()
function.
Here’s an example that demonstrates the usage of ftell()
:
#include <stdio.h> int main() { FILE *file = fopen("example.txt", "r"); if (file == NULL) { printf("Failed to open the file.\n"); return 1; } fseek(file, 0, SEEK_END); // Move the file position indicator to the end of the file long int fileSize = ftell(file); // Get the current position printf("File size: %ld bytes\n", fileSize); fclose(file); return 0; }
In this example, we open a file called “example.txt” in read mode using fopen()
. We then use fseek()
to move the file position indicator to the end of the file, and ftell()
to retrieve the current position, which gives us the file size. Finally, we print the file size in bytes.
It’s important to note that the return value of ftell()
may not be meaningful for binary files opened in text mode due to potential newline translation. Also, it may return -1 or encounter other errors in certain cases, so it’s good practice to check for errors when using this function.