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

63 lines
1.4 KiB
C

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#define BUFFER_SIZE 8
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[]){
int old, new;
old = open(argv[1], O_RDONLY);
new = open(argv[2], 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);
}
close(old);
close(new);
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) > 0) return 1;
}
return 0;
}