![The C Standard Library Reference](/c_standard_library/images/c-mini-logo.jpg)
- The C Standard Library
- C Library - Home
- C Library - <assert.h>
- C Library - <complex.h>
- C Library - <ctype.h>
- C Library - <errno.h>
- C Library - <fenv.h>
- C Library - <float.h>
- C Library - <inttypes.h>
- C Library - <iso646.h>
- C Library - <limits.h>
- C Library - <locale.h>
- C Library - <math.h>
- C Library - <setjmp.h>
- C Library - <signal.h>
- C Library - <stdalign.h>
- C Library - <stdarg.h>
- C Library - <stdbool.h>
- C Library - <stddef.h>
- C Library - <stdio.h>
- C Library - <stdlib.h>
- C Library - <string.h>
- C Library - <tgmath.h>
- C Library - <time.h>
- C Library - <wctype.h>
- C Standard Library Resources
- C Library - Quick Guide
- C Library - Useful Resources
- C Library - Discussion
- C Programming Resources
- C Programming - Tutorial
- C - Useful Resources
C Library - ftell() function
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.
Syntax
Following 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 Value
On 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 1
Basic 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: 10
Example 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