write homework 5
[assignments.git] / assgn5 / copy.c
1 #include <stdio.h>
2 #include <fcntl.h>
3 #include <unistd.h>
4
5 #include <sys/stat.h>
6
7 int main(int argc, char *argv[]) {
8
9 int cur, flag_append, flag_force;
10 int fd_from, fd_to, mode;
11 char buf[1];
12
13 flag_append = 0;
14 flag_force = 0;
15
16 while((cur = getopt(argc, argv, "af")) != -1) {
17 switch(cur) {
18
19 case 'a':
20 flag_append = 1;
21 break;
22
23 case 'f':
24 flag_force = 1;
25 break;
26
27 default:
28 printf("invalid argument\n");
29 return 1;
30 }
31 }
32
33 if(argc - optind != 2) {
34
35 printf("invalid number of args\n");
36 return 1;
37
38 } else if(flag_append && flag_force) {
39
40 printf("cannot simultaneously specify overwrite and append\n");
41 return 1;
42 }
43
44 if(access(argv[optind + 1], F_OK) != -1 && !flag_append && !flag_force) {
45
46 printf("destination file already exists, pass -f to overwrite\n");
47 return 1;
48 }
49
50 if(flag_force) mode = O_TRUNC;
51 else if(flag_append) mode = O_APPEND;
52 else mode = O_CREAT;
53
54 fd_from = open(argv[optind], O_RDONLY);
55 fd_to = open(argv[optind + 1], mode | O_WRONLY, S_IRWXU);
56
57 if(fd_from == -1) {
58
59 printf("could not open source file\n");
60 return 1;
61
62 } else if(fd_to == -1 && !flag_force && !flag_append) {
63
64 printf("could not create new destination file\n");
65 return 1;
66
67 } else if(fd_to == -1) {
68
69 }
70
71 while(read(fd_from, buf, 1) == 1)
72 write(fd_to, buf, 1);
73
74 close(fd_from);
75 close(fd_to);
76
77 return 0;
78 }