0 day streak
c / intermediate
Snippet

Determining File Size with fseek and ftell

To measure a file's size without reading every byte, you can seek to the end of the stream and query the position. This is essential for allocating exactly enough memory to load a file's content into a buffer.

snippet.c
c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <stdio.h>
long get_file_size(const char *path) {
FILE *file = fopen(path, "rb");
if (!file) return -1;
fseek(file, 0L, SEEK_END); // Move pointer to end
long size = ftell(file); // Get current offset
fclose(file);
return size;
}
int main(void) {
long bytes = get_file_size("example.bin");
if (bytes != -1) printf("File size: %ld bytes\n", bytes);
return 0;
}
Breakdown
1
fseek(file, 0L, SEEK_END)
Sets the file position indicator to the very end of the file.
2
ftell(file)
Returns the current value of the position indicator (number of bytes from start).