-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcp.c
56 lines (53 loc) · 1.25 KB
/
cp.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
//
// Created by andrew on 9/6/23.
//
#include "types.h"
#include "stat.h"
#include "user.h"
#include "fcntl.h"
int main(int argc, char *argv[]) {
if (argc != 3) {
printf(2, "Usage: cp source_file destination_file\n");
exit();
}
char *source = argv[1];
char *destination = argv[2];
int src_fd, dest_fd;
int r, w = 0;
char buf[1024];
struct stat st;
if (strcmp(source, destination) == 0) {
printf(2, "cp: %s and %s are the same file\n", source, destination);
return -1;
}
if ((src_fd = open(source, O_RDONLY)) < 0) {
printf(2, "cp: cannot open %s\n", source);
return -1;
}
if (fstat(src_fd, &st) < 0) {
printf(2, "cp: cannot stat %s\n", source);
close(src_fd);
return -1;
}
if (st.type != T_FILE) {
printf(2, "cp: %s is not a file\n", source);
close(src_fd);
return -1;
}
if ((dest_fd = open(destination, O_CREATE | O_WRONLY)) < 0) {
printf(2, "cp: cannot create %s\n", destination);
close(src_fd);
return -1;
}
while ((r = read(src_fd, buf, sizeof(buf))) > 0) {
if ((w = write(dest_fd, buf, r)) != r) {
break;
}
}
if (r < 0 || w < 0) {
printf(2, "cp: error copying %s to %s\n", source, destination);
}
close(src_fd);
close(dest_fd);
return 0;
}