ls-l.c
Fri May 10 2024 02:28:34 GMT+0000 (Coordinated Universal Time)
Saved by
@exam123
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <dirent.h>
#include <pwd.h>
#include <grp.h>
#include <time.h>
#include <sys/stat.h>
void print_permission(mode_t mode) {
printf((S_ISDIR(mode)) ? "d" : "-");
printf((mode & S_IRUSR) ? "r" : "-");
printf((mode & S_IWUSR) ? "w" : "-");
printf((mode & S_IXUSR) ? "x" : "-");
printf((mode & S_IRGRP) ? "r" : "-");
printf((mode & S_IWGRP) ? "w" : "-");
printf((mode & S_IXGRP) ? "x" : "-");
printf((mode & S_IROTH) ? "r" : "-");
printf((mode & S_IWOTH) ? "w" : "-");
printf((mode & S_IXOTH) ? "x" : "-");
}
void ls_l(const char *dirname) {
DIR *dir;
struct dirent *entry;
struct stat file_stat;
if ((dir = opendir(dirname)) == NULL) {
perror("opendir");
exit(EXIT_FAILURE);
}
while ((entry = readdir(dir)) != NULL) {
char path[PATH_MAX];
snprintf(path, PATH_MAX, "%s/%s", dirname, entry->d_name);
if (stat(path, &file_stat) == -1) {
perror("stat");
exit(EXIT_FAILURE);
}
struct passwd *user_info = getpwuid(file_stat.st_uid);
struct group *group_info = getgrgid(file_stat.st_gid);
printf("%20s %-8s %-8s %lld ", entry->d_name, user_info->pw_name, group_info->gr_name, (long long)file_stat.st_size);
print_permission(file_stat.st_mode);
struct tm *time_info = localtime(&file_stat.st_mtime);
char time_str[80];
strftime(time_str, sizeof(time_str), "%b %d %H:%M", time_info);
printf(" %s\n", time_str);
}
closedir(dir);
}
int main(int argc, char *argv[]) {
ls_l(argv[1]);
return 0;
}
content_copyCOPY
Comments