(source)
1
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <unistd.h>
5 #include <fcntl.h> // open and O_RDWR
6 #include <sys/stat.h> // struct stat
7 #include <sys/mman.h> // mmap, munmap, ...
8
9
10
11
12 int main(int argc, char* argv[])
13 {
14 int fd = open("test.bak", O_RDWR);
15
16 if ( fd < 0 ) {
17 fprintf(stderr, "Cannot open input file test.bak for update\n");
18 exit(1);
19 }
20 struct stat s;
21
22 fstat(fd, &s);
23
24 char *buf;
25
26 buf = mmap(0, s.st_size, PROT_WRITE, MAP_SHARED, fd, 0);
27
28 if ( buf == (void *) -1 ) {
29 fprintf(stderr, "mmap failed size = %lu\n", s.st_size);
30 exit(2);
31 }
32 int i;
33 printf("\nInitial test.bak contents:\n\n");
34 for(i = 0; i < s.st_size; i++) {
35 printf("%c", buf[i]);
36 }
37
38 // Reverse the characters in the file
39 char ch;
40 int j = s.st_size - 1;
41 for(i = 0; i < s.st_size / 2; i++, j--) {
42 // swap buf[i] and buf[j]
43 ch = buf[j];
44 buf[j] = buf[i];
45 buf[i] = ch;
46 }
47
48 printf("\n\nModified test.bak contents:\n\n");
49 for(i = 0; i < s.st_size; i++) {
50 printf("%c", buf[i]);
51 }
52
53
54 munmap(buf, s.st_size);
55 close(fd);
56
57
58
59 return 0;
60 }