Get File Size in C
To get the file size in C, you can use built-in functions such as fseek()
and ftell()
or the stat()
function to determine the size of a file in bytes.
Example 1: Using fseek()
and ftell()
In this example, we will open a file in binary mode, move the file pointer to the end using fseek()
, and then use ftell()
to obtain the file size. Finally, we close the file and display the size.
main.c
#include <stdio.h>
int main() {
FILE *file = fopen("example.txt", "rb");
if (file == NULL) {
printf("File not found.\n");
return 1;
}
fseek(file, 0, SEEK_END);
long size = ftell(file);
fclose(file);
printf("File size: %ld bytes\n", size);
return 0;
}
Explanation:
- We open the file
"example.txt"
in binary mode usingfopen()
and store the pointer in the variablefile
. - The
if
statement checks if the file was successfully opened. If not, an error message is printed. fseek(file, 0, SEEK_END)
moves the file pointer to the end of the file.ftell(file)
returns the current position of the file pointer, which is equal to the file size in bytes; this value is stored in the variablesize
.- We then close the file with
fclose()
and print the file size usingprintf()
.
Output:
File size: 1024 bytes
Example 2: Using stat()
Function
In this example, we will use the stat()
function from sys/stat.h
to retrieve metadata about the file, which includes the file size. The size is then printed to the console.
main.c
#include <stdio.h>
#include <sys/stat.h>
int main() {
struct stat st;
if (stat("example.txt", &st) != 0) {
printf("Could not retrieve file information.\n");
return 1;
}
printf("File size: %ld bytes\n", st.st_size);
return 0;
}
Explanation:
- We include the header
sys/stat.h
to access thestat()
function and related structures. - A
struct stat
variable namedst
is declared to hold the file information. - The
stat("example.txt", &st)
function call fillsst
with data about the file. If it returns a non-zero value, an error has occurred. - The file size in bytes is stored in
st.st_size
, which is then printed usingprintf()
.
Output:
File size: 1024 bytes
Conclusion
In this tutorial, we explored two different methods to get the file size in C. The first method uses fseek()
and ftell()
to navigate the file pointer, while the second method leverages the stat()
function to retrieve file metadata.