Thursday, March 28, 2013

Getting FILE information Via Stat in C Language

We know that Linux/Unix file system stores information for every file. Some of the information can be obtain by stat - A Unix system call. This system call is defined in < sys/stat.h> header file.

stat structure has the following fields.

struct stat {
    dev_t     st_dev;     /* ID of device containing file */
    ino_t     st_ino;     /* inode number */
    mode_t    st_mode;    /* protection */
    nlink_t   st_nlink;   /* number of hard links */
    uid_t     st_uid;     /* user ID of owner */
    gid_t     st_gid;     /* group ID of owner */
    dev_t     st_rdev;    /* device ID (if special file) */
    off_t     st_size;    /* total size, in bytes */
    blksize_t st_blksize; /* blocksize for file system I/O */
    blkcnt_t  st_blocks;  /* number of 512B blocks allocated */
    time_t    st_atime;   /* time of last access */
    time_t    st_mtime;   /* time of last modification */
    time_t    st_ctime;   /* time of last status change */
};


Now lets write a small program to get the file information using stat system call.

// File name Stat.c

#include <unistd.h>
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
int main(int argc, char **argv)
{
    if(argc != 2)   
        return 1;

    struct stat fileInfo;
    // getting file information into fileInfo using stat
    if(stat(argv[1],&fileInfo) < 0)   
        return 1;

    // printing file information
    printf("Information for %s\n",argv[1]);
    printf("---------------------------------------------------\n");
    printf("File Size: \t\t%d bytes\n",fileInfo.st_size);
    printf("Number of Links: \t%d\n",fileInfo.st_nlink);
    printf("File inode: \t\t%d\n",fileInfo.st_ino);

    // S_ISDIR, S_IRUSR,....are marcos
    printf("File Permissions Are: \t");
    printf( (S_ISDIR(fileInfo.st_mode)) ? "d" : "-");
    printf( (fileInfo.st_mode & S_IRUSR) ? "r" : "-");
    printf( (fileInfo.st_mode & S_IWUSR) ? "w" : "-");
    printf( (fileInfo.st_mode & S_IXUSR) ? "x" : "-");
    printf( (fileInfo.st_mode & S_IRGRP) ? "r" : "-");
    printf( (fileInfo.st_mode & S_IWGRP) ? "w" : "-");
    printf( (fileInfo.st_mode & S_IXGRP) ? "x" : "-");
    printf( (fileInfo.st_mode & S_IROTH) ? "r" : "-");
    printf( (fileInfo.st_mode & S_IWOTH) ? "w" : "-");
    printf( (fileInfo.st_mode & S_IXOTH) ? "x" : "-");
    printf("\n");

    return 0;
}


To Run: gcc Stat.c
              ./a.out Stat.c  // giving Stat.c file name as input

Out Put: 
Information for Stat.c
----------------------------------------
File Size:         1256 bytes
Number of Links:     1
File inode:         2367639
File Permissions Are:     -rw-r--r--

No comments:

Post a Comment