summaryrefslogtreecommitdiff
path: root/src/cmd/ls
diff options
context:
space:
mode:
authorJacob McDonnell <jacob@jacobmcdonnell.com>2024-03-05 18:46:44 -0500
committerJacob McDonnell <jacob@jacobmcdonnell.com>2024-03-05 18:46:44 -0500
commitc40f400f6ab879e08d54de753aabc987fd6ba07a (patch)
tree295f95070362d14d987638b558ad6bb1ba2415e2 /src/cmd/ls
parente32262d86c90e2ac73b2c38a47a1bb6b60935098 (diff)
Added a simple shell, jsh
Diffstat (limited to 'src/cmd/ls')
-rwxr-xr-xsrc/cmd/ls/ls.c78
-rwxr-xr-xsrc/cmd/ls/makefile12
2 files changed, 90 insertions, 0 deletions
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 <stdio.h>
+#include <sys/types.h>
+#include <dirent.h>
+#include <string.h>
+#include <stdlib.h>
+#include <errno.h>
+#include <sys/stat.h>
+
+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);
+}
+
diff --git a/src/cmd/ls/makefile b/src/cmd/ls/makefile
new file mode 100755
index 0000000..d6a3c8d
--- /dev/null
+++ b/src/cmd/ls/makefile
@@ -0,0 +1,12 @@
+CFLAGS=-Wall -Werror
+
+build: ls
+ @cp ls $(PROROOT)/build/bin/ls
+
+ls: ls.c
+ $(CC) $(CFLAGS) -o ls ls.c
+
+clean:
+ @rm -r ls
+
+.PHONY: build clean