commit d266c91f54877b6b278fcc3b7208671828276078
parent 1edc320acd39afa98396b9940741ca2de4940061
Author: qorg11 <qorg@vxempire.xyz>
Date: Tue, 29 Dec 2020 00:23:48 +0100
* Add recursive directory listing to ls.c
* Now you can actually give it a directory
This is very ugly code, and it has to be fixed.
Diffstat:
M | src/ls.c | | | 58 | ++++++++++++++++++++++++++++++++++++++++++++++++++-------- |
1 file changed, 50 insertions(+), 8 deletions(-)
diff --git a/src/ls.c b/src/ls.c
@@ -1,15 +1,41 @@
#include <stdio.h>
#include <dirent.h>
#include <getopt.h>
+#include <string.h>
+
+int
+recursive_list_dirs(const char *directory)
+{
+
+ DIR *dir;
+ struct dirent *ent;
+ if (!(dir = opendir(directory)))
+ return -1;
+
+ while((ent = readdir(dir)) != NULL) {
+ if(ent->d_type == DT_DIR) {
+ char path[1024];
+ if (strcmp(ent->d_name, ".") == 0||strcmp(ent->d_name, "..") == 0)
+ continue;
+ snprintf(path, sizeof(path), "%s/%s", directory, ent->d_name);
+ printf("%s/%s\n",path,ent->d_name);
+ recursive_list_dirs(path);
+ }
+ else printf("%s\n",ent->d_name);
+ }
+ closedir(dir);
+
+ return 0;
+}
int
main(int argc, char *argv[])
{
int c;
- int all, show_slash, show_line;
- all = show_slash = show_line = 0;
+ int all, show_slash, show_line, recursive;
+ all = show_slash = show_line = recursive = 0;
- while ((c = getopt(argc,argv,"lap")) != -1)
+ while ((c = getopt(argc,argv,"lapR")) != -1)
{
switch(c)
{
@@ -22,12 +48,28 @@ main(int argc, char *argv[])
case 'l':
show_line = 1;
break;
+ case 'R':
+ recursive = 1;
+ break;
}
}
- DIR *dir = opendir(".");
+ if(recursive)
+ {
+ recursive_list_dirs(argv[1]);
+ }
+ char directory[256];
+ if(!argv[optind])
+ strcpy(directory,".");
+ else strcpy(directory,argv[optind]); /* Very dirty code, i'll fix it
+ * later */
+ DIR *dir = opendir(directory);
struct dirent *ent;
-
+ if(recursive)
+ {
+ recursive_list_dirs(directory);
+ return 0;
+ }
if(dir != NULL)
{
while((ent = readdir(dir)) != NULL)
@@ -35,9 +77,9 @@ main(int argc, char *argv[])
if(ent->d_name[0] == '.' && !all)
continue;
if(!show_line) {
- if(ent->d_type == DT_DIR && show_slash)
- printf("%s/ ",ent->d_name);
- else printf("%s ",ent->d_name);
+ if(ent->d_type == DT_DIR && show_slash)
+ printf("%s/ ",ent->d_name);
+ else printf("%s ",ent->d_name);
}
else printf("%s\n",ent->d_name);
}