forked from MeiK2333/apue
-
Notifications
You must be signed in to change notification settings - Fork 0
/
14.8.c
53 lines (44 loc) · 1.19 KB
/
14.8.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
#include "apue.h"
#include <fcntl.h>
#include <sys/mman.h>
#define COPYINCR (1024*1024*1024)
int main(int argc, char *argv[]) {
int fdin, fdout;
void *src, *dst;
size_t copysz;
struct stat sbuf;
off_t fsz = 0;
if (argc != 3) {
err_quit("usage: %s <fromfile> <tofile>", argv[0]);
}
if ((fdin = open(argv[1], O_RDONLY)) < 0) {
err_sys("can't open %s for reading", argv[1]);
}
if ((fdout = open(argv[2], O_RDWR | O_CREAT | O_TRUNC, FILE_MODE)) < 0) {
err_sys("can't open %s for writing", argv[2]);
}
if (fstat(fdin, &sbuf) < 0) {
err_sys("stat error");
}
if (ftruncate(fdout, sbuf.st_size) < 0) {
err_sys("ftruncate error");
}
while (fsz < sbuf.st_size) {
if ((sbuf.st_size - fsz) > COPYINCR) {
copysz = COPYINCR;
} else {
copysz = sbuf.st_size - fsz;
}
if ((src = mmap(0, copysz, PROT_READ, MAP_SHARED, fdin, fsz)) == MAP_FAILED) {
err_sys("mmap error for input");
}
if ((dst = mmap(0, copysz, PROT_READ | PROT_WRITE, MAP_SHARED, fdout, fsz)) == MAP_FAILED) {
err_sys("mmap error for output");
}
memcpy(dst, src, copysz);
munmap(src, copysz);
munmap(dst, copysz);
fsz += copysz;
}
exit(0);
}