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

 $ 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);
}
Android Android Commands Android Java Applications Application Libraries Bash / Shell Scripts Bluetooth driver Build Frameworks Commands and Packages Core Kernel C Programs Development Environment Setup Documents / Books Errors & Failures File Systems Framebuffer / Display Driver git Go Language Programs Hardware Platforms Home Kernel & Device Drivers Kernel Booting and Porting Linux, OS Concepts and Networking Linux Device Drivers Linux Host, Ubuntu, SysAdmin Linux Kernel Linux Networking Middleware Libraries, HAL NDK / Middleware / HAL Network Driver OS Concepts PHP Procfs Filesystem Programming Languages RaspberryPi Scripting and Automation Search Engine Optimisation ( SEO ) Social Media Socurce Code Management ( SCM ) System Administration, Security Testing and Debugging Uncategorized Userspace Utilities Web design and development Wordpress Yocto / Bitbake / Openembedded

Leave a Reply