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

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

  1. FILE *file is used to open the file example.txt in binary mode using fopen().
  2. The fseek(file, 0, SEEK_END) function moves the file pointer to the end of the file.
  3. ftell(file) returns the current position of the file pointer, which is equivalent to the file size in bytes.
  4. Optionally, fseek(file, 0, SEEK_SET) resets the pointer to the beginning of the file.
  5. The file size is printed using printf() and the file is then closed with fclose().

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

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

  1. The struct stat st is declared to store file status information.
  2. The stat() function is called with the file name "example.txt" and the address of st to fill in file information.
  3. If stat() returns 0, the call is successful and st.st_size contains the file size in bytes.
  4. 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.