From ecc54f4be44fa1fd1ce79b0458a04eef2667cba8 Mon Sep 17 00:00:00 2001 From: dzwdz Date: Sat, 3 Sep 2022 23:12:31 +0200 Subject: user: implement a basic mkdir --- src/user/app/shell/builtins.c | 14 ++++++++++++++ src/user/lib/include/sys/stat.h | 7 +------ src/user/lib/sysstat.c | 24 ++++++++++++++++++++++++ 3 files changed, 39 insertions(+), 6 deletions(-) create mode 100644 src/user/lib/sysstat.c diff --git a/src/user/app/shell/builtins.c b/src/user/app/shell/builtins.c index 5af11e4..0f0125c 100644 --- a/src/user/app/shell/builtins.c +++ b/src/user/app/shell/builtins.c @@ -5,6 +5,7 @@ #include #include #include +#include #include #include @@ -187,6 +188,18 @@ static void cmd_ls(int argc, char **argv) { } } +static void cmd_mkdir(int argc, char **argv) { + // TODO mkdir -p + if (argc < 2) { + eprintf("no arguments"); + return; + } + for (int i = 1; i < argc; i++) { + if (mkdir(argv[i], 0777) < 0) + perror(argv[i]); + } +} + static void cmd_rm(int argc, char **argv) { if (argc < 2) { eprintf("no arguments"); @@ -241,6 +254,7 @@ struct builtin builtins[] = { {"hd", cmd_hexdump}, {"hexdump", cmd_hexdump}, {"ls", cmd_ls}, + {"mkdir", cmd_mkdir}, {"rm", cmd_rm}, {"sleep", cmd_sleep}, {"touch", cmd_touch}, diff --git a/src/user/lib/include/sys/stat.h b/src/user/lib/include/sys/stat.h index 78a8fc1..5776f1e 100644 --- a/src/user/lib/include/sys/stat.h +++ b/src/user/lib/include/sys/stat.h @@ -11,9 +11,4 @@ static inline int fstat(int fd, struct stat *sb) { return -1; } -static inline int mkdir(const char *path, mode_t mode) { - // TODO - (void)path; (void)mode; - errno = ENOSYS; - return -1; -} +int mkdir(const char *path, mode_t mode); diff --git a/src/user/lib/sysstat.c b/src/user/lib/sysstat.c new file mode 100644 index 0000000..df192c5 --- /dev/null +++ b/src/user/lib/sysstat.c @@ -0,0 +1,24 @@ +#include +#include +#include +#include + +int mkdir(const char *path, mode_t mode) { + // TODO error when directory already exits + // TODO fopen-like wrapper that calls open() with a processed path + (void)mode; + size_t plen = strlen(path); + char *tmp = NULL; + /* ensure trailing slash */ + if (plen >= 1 && path[plen - 1] != '/') { + tmp = malloc(plen + 2); + memcpy(tmp, path, plen); + tmp[plen] = '/'; + tmp[plen + 1] = '\0'; + path = tmp; + } + FILE *f = fopen(path, "a"); /* sets errno */ + if (f) fclose(f); + free(tmp); + return f == NULL ? -1 : 0; +} -- cgit v1.2.3