From 54c5165f0ebbf3202c9d5bc2e486551efb93584a Mon Sep 17 00:00:00 2001 From: Your Name Date: Mon, 16 Oct 2023 20:21:47 +0300 Subject: [PATCH] cp fixed --- TODO | 6 +++++- coreutils/cp.c | 41 +++++++++++++++++++++++++++++------------ tst/pst/test | 1 + 3 files changed, 35 insertions(+), 13 deletions(-) create mode 100644 tst/pst/test diff --git a/TODO b/TODO index 1329940..84f18f2 100644 --- a/TODO +++ b/TODO @@ -1,9 +1,13 @@ +*1/2: +cp +ln + +*Todo: chmod chown printf shuf id -ln du df dd diff --git a/coreutils/cp.c b/coreutils/cp.c index ef91cf7..a442ac5 100644 --- a/coreutils/cp.c +++ b/coreutils/cp.c @@ -8,6 +8,19 @@ #include #include +char *make_path(const char *src, const char *dst) { + size_t len = strlen(src) + strlen(dst) + 2; + char *full_path = malloc(len + 1); + if (full_path == NULL) { + fprintf(stderr, "cp: malloc() returned NULL\n"); + return NULL; + } + + snprintf(full_path, len, "%s/%s", src, dst); + return full_path; +} + + int write_to_file(const char *src, const char *dst) { int ifd = open(src, O_RDONLY); if (ifd < 0) @@ -35,12 +48,10 @@ int copyf(const char *src, const char *dst) { return 1; char *bname = basename(copy); - char *new_path = malloc(strlen(dst) + strlen(bname) + 1); - if (!new_path) + char *new_path = make_path(bname, dst); + if (new_path == NULL) return 1; - sprintf(new_path, "%s/%s", dst, bname); - int ret = write_to_file(src, new_path); free(new_path); @@ -70,6 +81,7 @@ int get_stat(const char *path, struct stat *stat_path) { } int cptree(const char *src, const char *dst) { + printf("%s %s\n", src, dst); struct stat stat_path; get_stat(src, &stat_path); @@ -83,6 +95,10 @@ int cptree(const char *src, const char *dst) { return 0; } + else { + mkdir(dst, 0777); + } + DIR *dir = opendir(src); if (dir == NULL) { fprintf(stderr, "cp: %s: Can`t open directory\n", src); @@ -94,17 +110,18 @@ int cptree(const char *src, const char *dst) { if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, "..")) continue; - size_t len = strlen(src) + strlen(ep->d_name) + 2; - char *full_path = malloc(len + 1); - if (full_path == NULL) { - fprintf(stderr, "rm: malloc() returned NULL\n"); + char *src_path = make_path(src, ep->d_name); + if (src_path == NULL) return 1; - } - snprintf(full_path, len, "%s/%s", src, ep->d_name); + char *dst_path = make_path(dst, ep->d_name); + if (dst_path == NULL) + return 1; - copy(full_path, dst); - free(full_path); + cptree(src_path, dst_path); + + free(src_path); + free(dst_path); } closedir(dir); diff --git a/tst/pst/test b/tst/pst/test new file mode 100644 index 0000000..1381bd7 --- /dev/null +++ b/tst/pst/test @@ -0,0 +1 @@ +hshshs