How to Identify File Size in C Using Linux stat System Call

In Linux programming, determining the size of a file is a common task. One efficient way to achieve this in C is by using the stat system call. This system call provides detailed information about a file, including its size. In this blog post, we’ll delve into how to use the stat system call to identify the size of a file in a C program, complete with examples to illustrate the concept.

Understanding the stat System Call

The stat system call is a powerful function in Unix-like operating systems that retrieves information about a file. It fills a struct stat with details about the file, such as its size, permissions, and modification time. The file size can be accessed via the st_size field in the struct stat.

Key Components of stat

  1. struct stat: This structure contains several fields related to the file’s attributes. The st_size field holds the size of the file in bytes.
  2. stat() Function: The stat() function takes two arguments:
  • The file path as a string.
  • A pointer to a struct stat where the file’s information will be stored.

Example C Program

Here is a simple C program that uses the stat system call to determine the size of a file:

#include <stdio.h>
#include <sys/stat.h>
#include <errno.h>

int main(int argc, char *argv[]) {
    if (argc != 2) {
        fprintf(stderr, "Usage: %s <file_path>\n", argv[0]);
        return 1;
    }

    struct stat file_stat;
    if (stat(argv[1], &file_stat) == -1) {
        perror("stat");
        return 1;
    }

    printf("Size of file '%s': %ld bytes\n", argv[1], file_stat.st_size);

    return 0;
}

How the Program Works

  1. Include Necessary Headers: We include <stdio.h> for standard I/O functions, <sys/stat.h> for the stat function and struct stat, and <errno.h> for error handling.
  2. Check Command-Line Arguments: The program expects a single argument, which is the path to the file. If the argument count is incorrect, it prints a usage message and exits.
  3. Call stat(): The stat() function is used to retrieve information about the file. If it fails, an error message is printed using perror().
  4. Print File Size: If successful, the program prints the size of the file using the st_size field from the struct stat.

Common Errors and Troubleshooting

  • File Not Found: If the file path is incorrect or the file does not exist, stat() will fail, and an error message will be displayed.
  • Permission Denied: If the program lacks permissions to read the file, stat() will also fail.

Conclusion

The stat system call is a fundamental tool in Linux programming for accessing file attributes. By using stat() in your C programs, you can easily retrieve and display file sizes, among other details. This method is efficient and integrates seamlessly with other file-related operations.

Leave a Comment