// UNIX cp copy // Wrote for Computer Networks and Systems lab classes // AUTHOR : Sergiusz Warga #include #include #include #include #include #include #define BUFFER_SIZE 8 // TODO: Think about it. enum ERROR{NO_ARGUMENTS, WRONG_ARGUMENT, DUNNO}; int print_error_message(enum ERROR error_type) { if (error_type == NO_ARGUMENTS) { fprintf(stderr,"cp: missing file operand\n"); // TODO: Maybe replace "cp" with argv[0]? fprintf(stderr,"Try cp --help for more information.\n"); return 0; } else if (error_type == WRONG_ARGUMENT) { fprintf(stderr, "cp: unrecognized option\n"); fprintf(stderr,"Try cp --help for more information.\n"); } else if (error_type == DUNNO) { fprintf(stderr, "Something went wrong!\n"); } return 0; } int print_help() { printf("HELP\n"); return 0; } int is_dir(const char *name) { struct stat path; stat(name, &path); return S_ISDIR(path.st_mode); } int cp(char *old_name, char *new_name) { // int cp(char *old_argv, char *new_argv) { // char *old_name, *new_name; // strncpy(old_name, old_argv, sizeof(old_argv)); // strncpy(new_name, new_argv, sizeof(new_argv)); int old, new; if (is_dir(new_name)) { printf("%s\n", new_name); strncat(new_name, "/", 1); printf("%s\n", new_name); strncat(new_name, old_name, sizeof(old_name)); printf("%s\n", new_name); } printf("Moving %s to %s\n", old_name, new_name); old = open(old_name, O_RDONLY); new = open(new_name, O_CREAT | O_WRONLY); char buffer[BUFFER_SIZE]; int read_bytes; while ((read_bytes = read(old, buffer, sizeof(buffer))) > 0) { write(new, buffer, read_bytes); } printf("%s moved to %s\n", old_name, new_name); close(old); close(new); return 0; } int copy_mod_bits(char *old_name, char *new_name) { struct stat mod_bits; stat(old_name, &mod_bits); chmod(new_name, mod_bits.st_mode); return 0; } int main(int argc, char *argv[]) { if (argc == 1) { print_error_message(NO_ARGUMENTS); return 1; } if (argc == 2) { if (strcmp(argv[1], "--help") == 0) { print_help(); return 0; } else { print_error_message(WRONG_ARGUMENT); return 2; } } if (argc == 3) { if (cp(argv[1], argv[2]) > 0) return 1; copy_mod_bits(argv[1], argv[2]); } if (argc > 3) { int no_of_old_files = argc - 2; for (int i = 1; i <= no_of_old_files; ++i) { printf("TOOO %s\n", argv[argc-1]); if (cp(argv[i], argv[argc-1]) > 0) return 1; copy_mod_bits(argv[i], argv[argc-1]); } } return 0; }