How to print file properties using stat() function in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <time.h>     
 
void printFileProperties(struct stat stats) {
    struct tm dt;
 
    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("mode");
     
    printf("File size: %d bytes\n", (int)stats.st_size);
	
	printf("Access time %s", ctime(&stats.st_atime));
    printf("Modify time %s", ctime(&stats.st_mtime));
    
	dt = *(gmtime(&stats.st_ctime));
    printf("Created time: %d-%d-%d %d:%d:%d\n", dt.tm_mday, dt.tm_mon, dt.tm_year + 1900, 
	                                            dt.tm_hour, dt.tm_min, dt.tm_sec);
}
     
int main()
{
    char file[100] = "d:\\data.txt";
    struct stat stats;
 
    printf("File: %s\n", file);
     
    if (stat(file, &stats) == 0) {
        printFileProperties(stats);
    }
    else {
        printf("Unable to get file properties\n");
    }
     
    return 0;
}
         
           
           
           
/*
run:
           
File: d:\data.txt
read write modeFile size: 40 bytes
Access time Sun Jul 12 10:35:03 2020
Modify time Sun Jul 12 10:35:03 2020
Created time: 12-6-2020 7:35:3
        
*/

 



answered Jul 12, 2020 by avibootz
edited Jul 12, 2020 by avibootz

Related questions

1 answer 151 views
1 answer 172 views
1 answer 155 views
1 answer 162 views
1 answer 46 views
1 answer 191 views
...