Determine the Size of a File in C
To determine the size of a file in C, you can use the combination of fseek() and ftell(), or use stat() function. In this tutorial, we have covered examples for these two approaches.
Example 1: Using fseek() and ftell()
In this example, we will open a file in binary mode, use fseek() to move the file pointer to the end, and then use ftell() to get the size of the file in bytes.
main.c
#include <stdio.h>
int main() {
FILE *file = fopen("example.txt", "rb");
if (file == NULL) {
perror("Error opening file");
return 1;
}
// Move file pointer to the end
fseek(file, 0, SEEK_END);
// Get the current file pointer position which is the file size in bytes
long size = ftell(file);
// Reset file pointer to the beginning (optional)
fseek(file, 0, SEEK_SET);
printf("File size: %ld bytes\n", size);
fclose(file);
return 0;
}
Explanation:
FILE *fileis used to open the fileexample.txtin binary mode usingfopen().- The
fseek(file, 0, SEEK_END)function moves the file pointer to the end of the file. ftell(file)returns the current position of the file pointer, which is equivalent to the file size in bytes.- Optionally,
fseek(file, 0, SEEK_SET)resets the pointer to the beginning of the file. - The file size is printed using
printf()and the file is then closed withfclose().
Output:
File size: [number] bytes
Example 2: Using the stat() Function
In this example, we will use the stat() system call to obtain information about a file, including its size. This approach is useful in environments that support the POSIX standard.
main.c
#include <stdio.h>
#include <sys/stat.h>
int main() {
struct stat st;
// Get file statistics for "example.txt"
if (stat("example.txt", &st) == 0) {
printf("File size: %ld bytes\n", st.st_size);
} else {
perror("Error getting file size");
return 1;
}
return 0;
}
Explanation:
- The
struct stat stis declared to store file status information. - The
stat()function is called with the file name"example.txt"and the address ofstto fill in file information. - If
stat()returns 0, the call is successful andst.st_sizecontains the file size in bytes. - The file size is then printed using
printf(). In case of an error,perror()displays an appropriate error message.
Output:
File size: [number] bytes
Conclusion
This tutorial provided two different methods to determine the size of a file in C. The first example used the fseek() and ftell() functions, which are straightforward and work well for simple file operations. The second example used the stat() function, offering a more robust solution especially in POSIX-compliant systems.
