Finding file size using seek and tell
What you'll learn: How to calculate the total size of a file in bytes by moving the file pointer to the end and checking its position.
The Bookmark Analogy
Imagine you are reading a physical book. To find out how many pages are in the book, you don't necessarily have to count every single one from the beginning. Instead, you can simply flip to the very last page and look at the page number written in the corner.
In C, we do the exact same thing with files. We move a "cursor" (the file pointer) to the very end of the file and ask the computer, "What is the number of the byte we are currently touching?" Since file positions start at zero, the position of the final byte tells us the total size.
Using fseek and ftell
To accomplish this, we use two functions you’ve encountered recently:
fseek(): We use this to jump directly to the end of the file.ftell(): We use this to report the current byte offset.
Here is the standard recipe for finding file size:
#include <stdio.h>
int main() {
FILE *file = fopen("example.txt", "r");
if (file == NULL) {
return 1;
}
// 1. Move the pointer to the very end (0 bytes from SEEK_END)
fseek(file, 0, SEEK_END);
// 2. Ask ftell for the current position
long size = ftell(file);
printf("The file is %ld bytes long.\n", size);
// 3. Optional: Move back to the start if you need to read the data
rewind(file);
fclose(file);
return 0;
}
How it works
When you call fseek(file, 0, SEEK_END), you are telling the operating system to put the "read head" at the end of the data stream. At this point, no data has been read, but the pointer is positioned perfectly after the last character.
When you call ftell(file), it returns a long integer representing how many bytes away from the start of the file you are. If ftell says you are at byte 500, and you are at the end, then the file is exactly 500 bytes large.
This is a common technique used to determine how much memory you need to allocate (using malloc) before reading a file's entire contents into a string.
Key takeaway
To find a file's size, seek to SEEK_END and then use ftell to get the byte count at that position.