How to Get the Length of a File in C
How to Get the Length of a File in C.
We can use the fseek() and ftell() functions from the standard library. Here is an example code that demonstrates how to get the length of a file:
FILE *file = fopen("example.txt", "r");
if (file == NULL) {
printf("Error opening file.\n");
return 1;
}
fseek(file, 0, SEEK_END);
long size = ftell(file);
fseek(file, 0, SEEK_SET);
printf("File size is %ld bytes.\n", size);
fclose(file);
FILE *file = fopen("example.txt", "r");
if (file == NULL) {
printf("Error opening file.\n");
return 1;
}
This code opens a file called “example.txt” in read mode and assigns the resulting FILE pointer to the variable file. If the file fails to open for some reason (e.g. if it doesn’t exist), fopen() returns NULL. The if statement checks whether file is NULL and, if it is, prints an error message to the console and exits the program with an error code of 1.
fseek(file, 0, SEEK_END);
long size = ftell(file);
fseek(file, 0, SEEK_SET);
These three lines of code use the fseek() and ftell() functions to determine the size of the file. The fseek() function moves the file pointer to the end of the file, which is accomplished by passing the arguments file, 0, and SEEK_END. The ftell() function then returns the position of the file pointer, which corresponds to the size of the file. The position of the file pointer is stored in the variable size.
After determining the size of the file, the file pointer is moved back to the beginning of the file using another call to fseek(). This time, the fseek() function is called with the arguments file, 0, and SEEK_SET.
printf("File size is %ld bytes.\n", size);
fclose(file);
Finally, the code prints the size of the file to the console using the printf() function. The “%ld” specifier is used to indicate that a long integer value should be printed, and the value of size is inserted into the string using the % syntax. Finally, the file is closed using the fclose() function to free up any resources associated with the open file.