OneCompiler

slip4&slip19

147

#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <pwd.h>
#include <grp.h>
#include <time.h>

void displayFileInfo(const char *filename) {
struct stat fileStat;
if (stat(filename, &fileStat) == -1) {
perror("Error getting file information");
return;
}

printf("File type: ");
if (S_ISREG(fileStat.st_mode))
    printf("Regular file\n");
else if (S_ISDIR(fileStat.st_mode))
    printf("Directory\n");
else if (S_ISLNK(fileStat.st_mode))
    printf("Symbolic link\n");
else if (S_ISCHR(fileStat.st_mode))
    printf("Character device\n");
else if (S_ISBLK(fileStat.st_mode))
    printf("Block device\n");
else if (S_ISFIFO(fileStat.st_mode))
    printf("FIFO/pipe\n");
else if (S_ISSOCK(fileStat.st_mode))
    printf("Socket\n");

printf("File access permissions: ");
printf((fileStat.st_mode & S_IRUSR) ? "r" : "-");
printf((fileStat.st_mode & S_IWUSR) ? "w" : "-");
printf((fileStat.st_mode & S_IXUSR) ? "x" : "-");
printf((fileStat.st_mode & S_IRGRP) ? "r" : "-");
printf((fileStat.st_mode & S_IWGRP) ? "w" : "-");
printf((fileStat.st_mode & S_IXGRP) ? "x" : "-");
printf((fileStat.st_mode & S_IROTH) ? "r" : "-");
printf((fileStat.st_mode & S_IWOTH) ? "w" : "-");
printf((fileStat.st_mode & S_IXOTH) ? "x" : "-");
printf("\n");

printf("File name: %s\n", filename);

struct passwd *user = getpwuid(fileStat.st_uid);
struct group *group = getgrgid(fileStat.st_gid);
if (user != NULL)
    printf("User ID: %s\n", user->pw_name);
if (group != NULL)
    printf("Group ID: %s\n", group->gr_name);

printf("File size: %ld bytes\n", fileStat.st_size);

printf("File access time: %s", ctime(&fileStat.st_atime));
printf("File modified time: %s", ctime(&fileStat.st_mtime));

}

int main() {
char filename[256];
printf("Enter the file name: ");
scanf("%s", filename);

displayFileInfo(filename);

return 0;

}
``