Find the size of a file in bytes in C
This post will discuss how to find the size of a file in bytes in C.
The Standard C doesn’t provide any direct method to determine the size of the file. However, we can use any of the following methods to get the file size:
1. Using stat() function
On Unix-like systems, we can use POSIX-compliant system calls. The stat() function takes the file path and returns a structure containing information about the file pointed by it. To get the size of the file in bytes, use the st_size field of the returned structure.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#include <iostream> #include <sys/stat.h> int main() { char filename[] = "somefile.txt"; struct stat st; stat(filename, &st); off_t size = st.st_size; std::cout << "The file size id " << size << " bytes\n"; return 0; } |
2. Using fstat() function
If we already have a file descriptor, use the fstat() function. The fstat() function is identical to the stat() function, except that the file is specified by the file descriptor.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
#include <iostream> #include <sys/stat.h> int main() { char filename[] = "somefile.txt"; FILE *fp = fopen(filename, "r"); if (fp == NULL) { printf("Cannot open source file.\n"); exit(1); } struct stat st; int fd = fileno(fp); // get file descriptor fstat(fd, &st); off_t size = st.st_size; std::cout << "The file size id " << size << " bytes\n"; return 0; } |
3. Using fseek() function
The idea is to seek the file to the end using the fseek() function with the SEEK_END offset, and then get the current position using the ftell() function. The return value by ftell() is the file size in bytes.
This approach is demonstrated below. Note that after getting the file size, we’re calling the rewind() function to seek the file to the beginning of the file. The rewind() function is equivalent to calling fseek(stream, 0L, SEEK_SET).
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
#include <iostream> int main() { char filename[] = "somefile.txt"; FILE *fp = fopen(filename, "r"); if (fp == NULL) { printf("Cannot open source file.\n"); exit(1); } fseek(fp, 0L, SEEK_END); // seek to the EOF int size = ftell(fp); // get the current position rewind(fp); // rewind to the beginning of file std::cout << "The file size id " << size << " bytes\n"; return 0; } |
That’s all about finding the size of a file in bytes in C.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)