AAE-CNAS-Labs/Topic-1/main.c

69 lines
1.5 KiB
C
Raw Normal View History

2021-03-03 15:22:13 +01:00
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
2021-03-03 16:32:13 +01:00
#include <fcntl.h>
#include <unistd.h>
2021-03-03 16:59:11 +01:00
#include <sys/stat.h>
2021-03-03 16:32:13 +01:00
#define BUFFER_SIZE 8
2021-03-03 15:22:13 +01:00
enum ERROR{NO_ARGUMENTS, WRONG_ARGUMENT};
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");
}
return 0;
}
int print_help() {
printf("HELP\n");
return 0;
}
int cp(char *argv[]){
2021-03-03 16:32:13 +01:00
int old, new;
old = open(argv[1], O_RDONLY);
new = open(argv[2], O_CREAT | O_WRONLY);
char buffer[BUFFER_SIZE];
2021-03-03 16:39:18 +01:00
int read_bytes;
2021-03-03 16:32:13 +01:00
2021-03-03 16:39:18 +01:00
while ((read_bytes = read(old, buffer, sizeof(buffer))) > 0) {
write(new, buffer, read_bytes);
2021-03-03 16:32:13 +01:00
}
2021-03-03 16:59:11 +01:00
struct stat mod_bits;
stat(argv[1], &mod_bits);
chmod(argv[2], mod_bits.st_mode);
2021-03-03 16:32:13 +01:00
close(old);
close(new);
2021-03-03 15:22:13 +01:00
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) {
2021-03-03 16:32:13 +01:00
if (cp(argv) > 0) return 1;
2021-03-03 15:22:13 +01:00
}
return 0;
}