From c40f400f6ab879e08d54de753aabc987fd6ba07a Mon Sep 17 00:00:00 2001 From: Jacob McDonnell Date: Tue, 5 Mar 2024 18:46:44 -0500 Subject: Added a simple shell, jsh --- src/cmd/ls/ls.c | 78 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100755 src/cmd/ls/ls.c (limited to 'src/cmd/ls/ls.c') diff --git a/src/cmd/ls/ls.c b/src/cmd/ls/ls.c new file mode 100755 index 0000000..a937457 --- /dev/null +++ b/src/cmd/ls/ls.c @@ -0,0 +1,78 @@ +/* TODO: + * - add flags + * - add option to print more file information + */ +#include +#include +#include +#include +#include +#include +#include + +void dirwalk(DIR *); +void error(char *); +void printdirent(struct dirent *); +void printfile(char *); + +/* print information about files and directories */ +int main(int argc, char **argv) +{ + DIR *dp; + if (argc == 1) { + if ((dp = opendir(".")) == NULL) { + perror("ls"); + return -1; + } + dirwalk(dp); + } else if (argc == 2) { + if ((dp = opendir(argv[1])) == NULL) { + perror("ls"); + return -1; + } + dirwalk(dp); + } else { + while (--argc > 0 && !ferror(stdout)) { + errno = 0; + if ((dp = opendir(*++argv)) == NULL) { + perror("ls"); + continue; + } + dirwalk(dp); + } + } +} + +/* dirwalk: read all the directory entries in a directory */ +void dirwalk(DIR *d) +{ + struct dirent *dir; + while ((dir = readdir(d)) != NULL) { + errno = 0; + if (strcmp(dir->d_name, ".") == 0 || strcmp(dir->d_name, "..") == 0) + continue; + printdirent(dir); + } + if (errno != 0) { + perror("ls"); + } +} + +/* printdirent: print a directory entry and any selected information */ +void printdirent(struct dirent *dir) +{ + printf("%s\n", dir->d_name); +} + +/* printfile: print a file and any other selected information */ +void printfile(char *name) +{ + struct stat stbuf; + int e = stat(name, &stbuf); + if (e != 0) { + perror("ls"); + return; + } + printf("%s\n", name); +} + -- cgit v1.2.3