-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmemmap.c
109 lines (78 loc) · 1.87 KB
/
memmap.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
/*
* Example of using mmap. Taken from Advanced Programming in the Unix
* Environment by Richard Stevens.
*/
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h> /* mmap() is defined in this header */
#include <fcntl.h>
#include <unistd.h>
#include <string.h> /* memcpy */
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
void err_quit (const char * mesg)
{
printf ("%s\n", mesg);
exit(1);
}
void err_sys (const char * mesg)
{
perror(mesg);
exit(errno);
}
int main (int argc, char *argv[])
{
int fdin, fdout, i;
char *src, *dst, buf[256];
struct stat statbuf;
src = dst = NULL;
if (argc != 3)
err_quit ("usage: memmap <fromfile> <tofile>");
/*
* open the input file
*/
if ((fdin = open (argv[1], O_RDONLY)) < 0) {
sprintf(buf, "can't open %s for reading", argv[1]);
perror(buf);
exit(errno);
}
/*
* open/create the output file
*/
if ((fdout = open (argv[2], O_RDWR | O_CREAT | O_TRUNC, 0644)) < 0) {
sprintf (buf, "can't create %s for writing", argv[2]);
perror(buf);
exit(errno);
}
struct stat s;
/*
* 1. find size of input file
*/
fstat( fdin, &s );
/*
* 2. go to the location corresponding to the last byte
*/
lseek( fdout, s.st_size - 1, SEEK_SET );
/*
* 3. write a dummy byte at the last location
*/
write( fdout, " ", 1 );
/*
* 4. mmap the input file
*/
mmap( NULL, s.st_size, PROT_READ, MAP_SHARED, fdin, 0 );
/*
* 5. mmap the output file
*/
mmap( NULL, s.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, fdout, 0 );
/*
* 6. copy the input file to the output file
*/
memcpy( dst, src, s.st_size );
/* Memory can be dereferenced using the * operator in C. This line
* stores what is in the memory location pointed to by src into
* the memory location pointed to by dest.
*/
*dst = *src;
}