-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathcp.c
43 lines (36 loc) · 760 Bytes
/
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
#include "types.h"
#include "stat.h"
#include "user.h"
#include "fcntl.h"
int
main(int argc, char *argv[])
{
char buf[512];
int fd, dfd, r, w;
char *src;
char *dest;
if(argc != 3){
printf(2, "Usage: cp src dest\n");
exit();
}
src = argv[1];
dest = argv[2];
if ((fd = open(src, O_RDONLY)) < 0) {
printf(2, "cp: cannot open source %s\n", src);
exit();
}
if ((dfd = open(dest, O_CREATE|O_WRONLY)) < 0) {
printf(2, "cp: cannot open destination %s\n", dest);
exit();
}
while ((r = read(fd, buf, sizeof(buf))) > 0) {
w = write(dfd, buf, r);
if (w != r || w < 0)
break;
}
if (r < 0 || w < 0)
printf(2, "cp: error copying %s to %s\n", src, dest);
close(fd);
close(dfd);
exit();
}