C program to Identify size of a file using Linux stat system call

This program uses “stat” system call to read the file size. In this post, we demonstrate with simple example, how you can read the filesize and print the value on terminal.

 $ vim file_size_using_stat.c 
#include <stdio.h>
#include <sys/stat.h>
#include <errno.h>
#include <stdlib.h>
 
int main(int argc, char **argv) {
        char *file = "/etc/init.d/README";
        long long size; //st_size can be a 64-bit int.
        struct stat *buf = malloc(sizeof(struct stat));
        errno = 0; //always set errno to zero first.
 
        if(stat(file, buf) == 0) {
                size = buf->st_size;
                printf("Size of \"%s\" is %lld bytes.\n", file, size);
        } else {
                perror(file);    //if stat fails, print a diagnostic.
        }
        return 0;
}
 $ gcc -o file_size_using_stat file_size_using_stat.c 
$ ./file_size_using_stat
Size of "/etc/init.d/README" is 2427 bytes.

OR using another program like below,

#include <sys/types.h>
#include <sys/stat.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
 
int main(int argc, char *argv[]) {
    struct stat sb;
 
    if (argc != 2) {
        fprintf(stderr, "Usage: %s <pathname>\n", argv[0]);
        exit(EXIT_FAILURE);
    }
 
    if (stat(argv[1], &sb) == -1) {
        perror("stat");
        exit(EXIT_FAILURE);
    }
 
    printf("File size: %lld bytes\n", (long long) sb.st_size);
    exit(EXIT_SUCCESS);
}

Leave a Comment