blob: d8d9fdb419ae100227ff5d272c74518481af6087 (
plain)
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
|
#include <unistd.h>
#include <fcntl.h>
#include <assert.h>
#include <stdio.h>
int main(int argc, char** argv)
{
if (argc != 3) {
printf("usage: cp <source> <destination>\n");
return 0;
}
int src_fd = open(argv[1], O_RDONLY);
if (src_fd < 0) {
perror("open src");
return 1;
}
int dst_fd = open(argv[2], O_WRONLY | O_CREAT);
if (dst_fd < 0) {
perror("open dst");
return 1;
}
for (;;) {
char buffer[BUFSIZ];
ssize_t nread = read(src_fd, buffer, sizeof(buffer));
if (nread < 0) {
perror("read src");
return 1;
}
if (nread == 0)
break;
ssize_t remaining_to_write = nread;
char* bufptr = buffer;
while (remaining_to_write) {
ssize_t nwritten = write(dst_fd, bufptr, remaining_to_write);
if (nwritten < 0) {
perror("write dst");
return 1;
}
assert(nwritten > 0);
remaining_to_write -= nwritten;
bufptr += nwritten;
}
}
close(src_fd);
close(dst_fd);
return 0;
}
|