C program to find file properties using stat() function

Write a C program to check file properties using stat() function. How to check file permissions, size, creation and modification date of a file in C programming. How to use stat() function to find various file properties.

Required knowledge

Basic Input Output, File handling, Pointers

stat() function in C

int stat(const char *path, struct stat *buf);

stat() function is used to list properties of a file identified by path. It reads all file properties and dumps to buf structure. The function is defined in sys/stat.h header file.

Here *path is a pointer to constant character pointing to file path. *buf is a stat type structure defined in sys/stat.h.

On success the function returns 0 and fills the buf structure with file properties. On error the function return -1 and sets error code. You can use this function to get various properties of a file.

Program to find file properties using stat()

/**
 * C program to find file permission, size, creation and last modification date of 
 * a given file.
 */

#include <stdio.h>
#include <unistd.h>
#include <sys/stat.h>
#include <time.h>


void printFileProperties(struct stat stats);


int main()
{
    char path[100];
    struct stat stats;

    printf("Enter source file path: ");
    scanf("%s", path);


    // stat() returns 0 on successful operation,
    // otherwise returns -1 if unable to get file properties.
    if (stat(path, &stats) == 0)
    {
        printFileProperties(stats);
    }
    else
    {
        printf("Unable to get file properties.\n");
        printf("Please check whether '%s' file exists.\n", path);
    }

    return 0;
}



/**
 * Function to print file properties.
 */
void printFileProperties(struct stat stats)
{
    struct tm dt;

    // File permissions
    printf("\nFile access: ");
    if (stats.st_mode & R_OK)
        printf("read ");
    if (stats.st_mode & W_OK)
        printf("write ");
    if (stats.st_mode & X_OK)
        printf("execute");

    // File size
    printf("\nFile size: %d", stats.st_size);

    // Get file creation time in seconds and 
    // convert seconds to date and time format
    dt = *(gmtime(&stats.st_ctime));
    printf("\nCreated on: %d-%d-%d %d:%d:%d", dt.tm_mday, dt.tm_mon, dt.tm_year + 1900, 
                                              dt.tm_hour, dt.tm_min, dt.tm_sec);

    // File modification time
    dt = *(gmtime(&stats.st_mtime));
    printf("\nModified on: %d-%d-%d %d:%d:%d", dt.tm_mday, dt.tm_mon, dt.tm_year + 1900, 
                                              dt.tm_hour, dt.tm_min, dt.tm_sec);

}

Output

Enter source file path: data/file3.txt

File access: read write
File size: 115
Created on: 4-1-2018 16:34:13
Modified on: 5-2-2018 19:1:10

Happy coding 😉