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

</>
Copy
#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:

  1. We open the file "example.txt" in binary mode using fopen() and store the pointer in the variable file.
  2. The if statement checks if the file was successfully opened. If not, an error message is printed.
  3. fseek(file, 0, SEEK_END) moves the file pointer to the end of the file.
  4. 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 variable size.
  5. We then close the file with fclose() and print the file size using printf().

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

</>
Copy
#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:

  1. We include the header sys/stat.h to access the stat() function and related structures.
  2. A struct stat variable named st is declared to hold the file information.
  3. The stat("example.txt", &st) function call fills st with data about the file. If it returns a non-zero value, an error has occurred.
  4. The file size in bytes is stored in st.st_size, which is then printed using printf().

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.