micro-utils/coreutils/ls.c

76 lines
1.3 KiB
C
Raw Normal View History

#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
#include <sys/types.h>
int list(const char *path, int flag, 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 */
struct dirent *ep;
DIR *dp = opendir(path);
if (dp == NULL) {
fprintf(stderr, "ls: %s: %s\n", path, strerror(errno));
return 1;
}
while ((ep = readdir(dp)) != NULL) {
if (ep->d_name[0] == '.' && !flag)
continue;
2023-10-13 15:34:16 +03:00
printf("%s ", ep->d_name);
}
closedir(dp);
2023-10-13 15:34:16 +03:00
printf("\n");
return 0;
}
int main(const int argc, const char **argv) {
int flag = 0;
int i;
for (i = 1; i < argc; i++) {
if (argv[i][0] != '-')
break;
else if (!strcmp(argv[i], "-a"))
flag = 1;
else if (!strcmp(argv[i], "-h")) {
printf("ls [-a (Show hidden files)] [Path]\n");
return 0;
}
}
if (i == argc)
return list(".", flag, 0);
if (i == argc - 1)
return list(argv[i], flag, 0);
else
for (int i = 1; i < argc; i++)
if (list(argv[i], flag, 1))
return 1;
return 0;
}