micro-utils/coreutils/ls.c

111 lines
2.3 KiB
C
Raw Normal View History

2023-10-20 00:19:46 +03:00
#include <time.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
2023-10-20 16:59:07 +03:00
#include <stdint.h>
#include <dirent.h>
#include <sys/stat.h>
#include <sys/types.h>
2023-10-20 00:19:46 +03:00
unsigned int a_flag;
unsigned int l_flag;
void PrintPerm(struct stat sb) {
printf("%c", (S_ISDIR(sb.st_mode)) ? 'd' : '-');
printf("%c%c%c", (sb.st_mode & S_IRUSR) ? 'r' : '-', (sb.st_mode & S_IWUSR) ? 'w' : '-', (sb.st_mode & S_IXUSR) ? 'x' : '-');
printf("%c%c%c", (sb.st_mode & S_IRGRP) ? 'r' : '-', (sb.st_mode & S_IWGRP) ? 'w' : '-', (sb.st_mode & S_IXGRP) ? 'x' : '-');
printf("%c%c%c", (sb.st_mode & S_IROTH) ? 'r' : '-', (sb.st_mode & S_IWOTH) ? 'w' : '-', (sb.st_mode & S_IXOTH) ? 'x' : '-');
}
2023-10-20 00:19:46 +03:00
int list(const char *path, int label) {
struct stat statbuf;
if (stat(path, &statbuf)) {
fprintf(stderr, "ls: unable to stat %s: %s\n", path, strerror(errno));
return 1;
}
/* If its file */
2023-10-16 20:57:30 +03:00
if (S_ISDIR(statbuf.st_mode) == 0) {
puts(path);
return 0;
}
/* Make label */
if (label)
printf("\n%s: \n", path);
/* Open and print dir */
DIR *dp = opendir(path);
if (dp == NULL) {
fprintf(stderr, "ls: %s: %s\n", path, strerror(errno));
return 1;
}
2023-10-20 00:19:46 +03:00
struct dirent *ep;
while ((ep = readdir(dp)) != NULL) {
2023-10-20 00:19:46 +03:00
if (ep->d_name[0] == '.' && !a_flag)
continue;
2023-10-20 00:19:46 +03:00
if (l_flag) {
struct stat sb;
if (lstat(ep->d_name, &sb) == -1) {
fprintf(stderr, "ls: lstat()\n");
return 1;
}
/* Permissions */
PrintPerm(sb);
/* Date and other info */
struct tm *tm = localtime(&sb.st_mtime);
char date[14];
if (strftime(date, sizeof(date), "%b %d %H:%M", tm) == 0) {
fprintf(stderr, "ls: strftime()\n");
return 1;
}
printf(" %jd %jd %s ", (uintmax_t)sb.st_mode, (uintmax_t)sb.st_size, date);
}
2023-10-13 15:34:16 +03:00
printf("%s ", ep->d_name);
2023-10-20 00:19:46 +03:00
printf("\n");
}
closedir(dp);
return 0;
}
int main(const int argc, const char **argv) {
int i;
for (i = 1; i < argc; i++) {
if (argv[i][0] != '-')
break;
else if (!strcmp(argv[i], "-a"))
2023-10-20 00:19:46 +03:00
a_flag = 1;
else if (!strcmp(argv[i], "-l"))
l_flag = 1;
else if (!strcmp(argv[i], "-h")) {
2023-10-20 00:19:46 +03:00
printf("ls [-a (Show hidden files)] [-l (use a long listing format (month / day / hour:min))] [Path]\n");
return 0;
}
}
if (i == argc)
2023-10-20 00:19:46 +03:00
return list(".", 0);
if (i == argc - 1)
2023-10-20 00:19:46 +03:00
return list(argv[i], 0);
else
for (int i = 1; i < argc; i++)
2023-10-20 00:19:46 +03:00
if (list(argv[i], 1))
return 1;
2023-10-20 00:19:46 +03:00
return 0;
}