2023-10-03 23:09:17 +03:00
|
|
|
#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)) {
|
2023-10-04 20:00:21 +03:00
|
|
|
fprintf(stderr, "ls: unable to stat %s: %s\n", path, strerror(errno));
|
2023-10-03 23:09:17 +03:00
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
|
|
|
/* If its file */
|
2023-10-16 20:57:30 +03:00
|
|
|
if (S_ISDIR(statbuf.st_mode) == 0) {
|
2023-10-03 23:09:17 +03:00
|
|
|
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) {
|
2023-10-04 20:00:21 +03:00
|
|
|
fprintf(stderr, "ls: %s: %s\n", path, strerror(errno));
|
2023-10-03 23:09:17 +03:00
|
|
|
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);
|
2023-10-03 23:09:17 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
closedir(dp);
|
2023-10-13 15:34:16 +03:00
|
|
|
printf("\n");
|
2023-10-03 23:09:17 +03:00
|
|
|
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")) {
|
2023-10-04 14:27:12 +03:00
|
|
|
printf("ls [-a (Show hidden files)] [Path]\n");
|
2023-10-03 23:09:17 +03:00
|
|
|
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;
|
|
|
|
}
|