#include #include #include #include #include #include #include #include #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_buffer(int ifd, int ofd) { char buf[4096]; size_t bytes = 0; while ((bytes = read(ifd, buf, sizeof(buf))) > 0) if (write(ofd, buf, bytes) != bytes) return 1; return 0; } int copy(const char *src, const char *dst) { int ifd = open(src, O_RDONLY); if (ifd < 0) return 1; int ofd = open(dst, O_CREAT | O_TRUNC | O_WRONLY, 0666); if (ofd < 0) { close(ifd); return 1; } if (write_buffer(ifd, ofd)) fprintf(stderr, "cp: (%s %s) %s\n", src, dst, strerror(errno)); close(ifd); close(ofd); return 0; } int get_stat(const char *path, struct stat *stat_path) { if (stat(path, stat_path)) { fprintf(stderr, "cp: unable to stat %s: %s\n", path, strerror(errno)); return 1; } return 0; } int cptree(const char *src, const char *dst) { struct stat stat_path; get_stat(src, &stat_path); printf("%s %s\n", src, dst); if (S_ISDIR(stat_path.st_mode) == 0) { if (copy(src, dst)) { fprintf(stderr, "cp: %s: copy() failed (%s)\n", src, strerror(errno)); return 1; } return 0; } else if (mkdir(dst, 0777) < 0) { fprintf(stderr, "cp: %s\n", strerror(errno)); } DIR *dir = opendir(src); if (dir == NULL) { fprintf(stderr, "cp: %s: Can`t open directory\n", src); return 1; } struct dirent *ep; while ((ep = readdir(dir)) != NULL) { if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, "..")) continue; char *src_path = make_path(src, ep->d_name); if (src_path == NULL) return 1; char *dst_path = make_path(dst, ep->d_name); if (dst_path == NULL) return 1; cptree(src_path, dst_path); free(src_path); free(dst_path); } closedir(dir); return 0; } int main(const int argc, const char **argv) { if (argc < 2 || !strcmp(argv[1], "-h")) { printf("cp [Src] [Dst]\n"); return 0; } return cptree(argv[1], argv[2]); }