-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsimple-copy.cpp
62 lines (52 loc) · 1.26 KB
/
simple-copy.cpp
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
57
58
59
60
61
62
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <cstring>
#include <iostream>
// 128 MiB buffer
constexpr size_t BUF_SIZE = 128 * 1024;
char buf[BUF_SIZE];
int main(int argc, char* argv[]) {
if (argc != 3) {
std::cerr << "Provide source and destination filenames\n";
exit(1);
}
struct stat src_stat = {};
if (stat(argv[1], &src_stat) < 0) {
perror(argv[0]);
exit(1);
}
int src_fd = open(argv[1], O_RDONLY);
if (src_fd < 0) {
perror(argv[0]);
exit(1);
}
int dst_fd = open(argv[2], O_WRONLY | O_CREAT, src_stat.st_mode);
if (dst_fd < 0) {
perror(argv[0]);
exit(1);
}
if (ftruncate(dst_fd, 0) < 0) {
perror(argv[0]);
exit(1);
}
while (true) {
ssize_t bytes_read = read(src_fd, buf, BUF_SIZE);
if (bytes_read < 0) {
perror(argv[0]);
exit(1);
}
ssize_t bytes_written = write(dst_fd, buf, bytes_read);
if (bytes_written < 0) {
perror(argv[0]);
exit(1);
}
if (bytes_read < ssize_t(BUF_SIZE)) {
break;
}
}
// ignore the error if it happens
close(src_fd);
close(dst_fd);
}