How to show file permissions and properties in Linux with C

1 Answer

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

void printFileProperties(struct stat stats) {
    struct tm dt;

    printf("File 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");

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

    dt = *(gmtime(&stats.st_mtime));
    printf("\nCreated on: %d-%d-%d %d:%d:%d", dt.tm_mday, dt.tm_mon + 1, dt.tm_year + 1900,
                                               dt.tm_hour, dt.tm_min, dt.tm_sec);
    dt = *(gmtime(&stats.st_ctime));
    printf("\nModified on: %d-%d-%d %d:%d:%d", dt.tm_mday, dt.tm_mon + 1, dt.tm_year + 1900,
                                              dt.tm_hour, dt.tm_min, dt.tm_sec);
}

int main(void)
{
    struct stat st;
    char filename[32] = ".profile";

    stat(filename, &st);
    
    printFileProperties(st);

    return 0;
}


/*
run:

File access: read execute
File size: 807
Created on: 29-3-2024 19:40:10
Modified on: 26-1-2025 5:58:16

*/

 



answered Jan 26, 2025 by avibootz
edited Jan 26, 2025 by avibootz

Related questions

1 answer 154 views
154 views asked Jun 17, 2016 by avibootz
1 answer 679 views
1 answer 170 views
1 answer 126 views
1 answer 243 views
...