The C library ftell() function returns the current file position of the given stream. This function is important for determining where in the file the next read or write operation will occur.
SyntaxFollowing is the C Library syntax of ftell() function −
long ftell(FILE *stream);Parameter
stream : A pointer to a FILE object that specifies the file stream. The FILE object is typically obtained by using the fopen() function.
Return ValueOn success, ftell() returns the current file position as a long integer. On failure, it returns -1L and sets the global variable errno to indicate the error.
Example 1Basic Usage of ftell()
In this example, we open a file, move the file position indicator, and then use ftell() to get the current position.
#include <stdio.h> int main() { FILE *file = fopen("example.txt", "r"); if (file == NULL) { perror("Failed to open file"); return 1; } // Move the file position indicator to the 10th byte fseek(file, 10, SEEK_SET); // Get the current position long position = ftell(file); if (position == -1L) { perror("ftell failed"); } else { printf("Current file position: %ld\n", position); } fclose(file); return 0; }Output
The above code produces following result−
Current file position: 10Example 2
Using ftell() to Determine File Length
This example shows how to use ftell() to find the length of a file by seeking to the end of the file.
#include <stdio.h> int main() { FILE *file = fopen("example.txt", "r"); if (file == NULL) { perror("Failed to open file"); return 1; } // Move the file position indicator to the end of the file fseek(file, 0, SEEK_END); // Get the current position, which is the file size long fileSize = ftell(file); if (fileSize == -1L) { perror("ftell failed"); } else { printf("File size: %ld bytes\n", fileSize); } fclose(file); return 0; }Output
After execution of above code, we get the following result
File size: 150 bytes
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4