Write a c program to print file details including owner access permissions, file access time, where file name is given as argument.
Below is the C program that retrieves and prints file details, including the owner, access permissions, and last access time, for a given file name provided as a command-line argument.
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <pwd.h>
#include <grp.h>
#include <time.h>
void print_file_details(const char *filename) {
struct stat file_stat;
// Get file statistics
if (stat(filename, &file_stat) == -1) {
perror("Failed to get file status");
exit(EXIT_FAILURE);
}
// Print owner
struct passwd *pw = getpwuid(file_stat.st_uid);
struct group *gr = getgrgid(file_stat.st_gid);
printf("File: %s\n", filename);
printf("Owner: %s (UID: %d)\n", pw->pw_name, file_stat.st_uid);
printf("Group: %s (GID: %d)\n", gr->gr_name, file_stat.st_gid);
// Print permissions
printf("Access Permissions: ");
printf((file_stat.st_mode & S_IRUSR) ? "r" : "-");
printf((file_stat.st_mode & S_IWUSR) ? "w" : "-");
printf((file_stat.st_mode & S_IXUSR) ? "x" : "-");
printf((file_stat.st_mode & S_IRGRP) ? "r" : "-");
printf((file_stat.st_mode & S_IWGRP) ? "w" : "-");
printf((file_stat.st_mode & S_IXGRP) ? "x" : "-");
printf((file_stat.st_mode & S_IROTH) ? "r" : "-");
printf((file_stat.st_mode & S_IWOTH) ? "w" : "-");
printf((file_stat.st_mode & S_IXOTH) ? "x" : "-");
printf("\n");
// Print last access time
char time_buffer[100];
struct tm *tm_info;
tm_info = localtime(&file_stat.st_atime);
strftime(time_buffer, sizeof(time_buffer), "%Y-%m-%d %H:%M:%S", tm_info);
printf("Last Access Time: %s\n", time_buffer);
}
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s \n", argv[0]);
exit(EXIT_FAILURE);
}
print_file_details(argv[1]);
return 0;
}