Skip to content

Commit 5970674

Browse files
committed
study
1 parent 0742652 commit 5970674

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

14.12.c

+57
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
#include <fcntl.h>
4+
#include <sys/mman.h>
5+
6+
#define FILE_MODE (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)
7+
8+
int main(int argc, char *argv[])
9+
{
10+
int fdin, fdout;
11+
void *src, *dst;
12+
struct stat statbuf;
13+
14+
if (3 != argc) {
15+
printf("usage: %s <fromfile> <tofile>\n", argv[0]);
16+
exit(-1);
17+
}
18+
19+
if ((fdin = open(argv[1], O_RDONLY)) < 0) {
20+
printf("can't open %s for reading\n", argv[1]);
21+
exit(-1);
22+
}
23+
24+
if ((fdout = open(argv[2], O_RDWR | O_CREAT | O_TRUNC, FILE_MODE)) < 0) {
25+
printf("can't create %s for writing\n", argv[2]);
26+
exit(-1);
27+
}
28+
29+
if (fstat(fdin, &statbuf) < 0) {
30+
printf("fstat error\n");
31+
exit(-1);
32+
}
33+
34+
if (lseek(fdout, statbuf.st_size - 1, SEEK_SET) == -1) {
35+
printf("lseek error\n");
36+
exit(-1);
37+
}
38+
39+
if (write(fdout, "", 1) != 1) {
40+
printf("lseek error\n");
41+
exit(-1);
42+
}
43+
44+
if ((src = mmap(0, statbuf.st_size, PORT_READ, MAP_SHARED, fdin, 0)) == MAP_FAILED) {
45+
printf("mmap error for input\n");
46+
exit(-1);
47+
}
48+
49+
if ((dst = mmap(0, statbuf.st_size, PORT_READ | PORT_WRITE, MAP_SHARED, fdout, 0)) == MAP_FAILED) {
50+
printf("mmap error for output\n");
51+
exit(-1);
52+
}
53+
54+
memcpy(dst, src, statbuf.st_size);
55+
56+
return 0;
57+
}

0 commit comments

Comments
 (0)