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)) {
|
|
|
|
fprintf(stderr, "unable to stat %s: %s\n", path, strerror(errno));
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
|
|
|
/* If its file */
|
|
|
|
if (!S_ISDIR(statbuf.st_mode)) {
|
|
|
|
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, "%s: %s\n", path, strerror(errno));
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
|
|
|
while ((ep = readdir(dp)) != NULL) {
|
|
|
|
if (ep->d_name[0] == '.' && !flag)
|
|
|
|
continue;
|
|
|
|
|
|
|
|
puts(ep->d_name);
|
|
|
|
}
|
|
|
|
|
|
|
|
closedir(dp);
|
|
|
|
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;
|
|
|
|
}
|