Skip to content

Commit efd56e4

Browse files
committed
add mmaptest.c
1 parent 2e27bc7 commit efd56e4

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

mmaptest.c

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
#include <fcntl.h>
4+
#include <unistd.h>
5+
#include <sys/mman.h>
6+
#include <sys/stat.h>
7+
#include <errno.h>
8+
9+
int main(int argc, char *argv[])
10+
{
11+
int fd, offset;
12+
char *data;
13+
struct stat sbuf;
14+
FILE *f;
15+
16+
if (argc != 2) {
17+
fprintf(stderr, "usage: mmapdemo offset\n");
18+
exit(1);
19+
}
20+
21+
f = fopen("./h1_1280_720_5m.mp4_mbstpos_gop1.txt", "w");
22+
fprintf(f, "sssssssssssssssssssssssssss");
23+
fflush(f);
24+
//this line will cause no such device error
25+
printf("fd: %d\n", fd);
26+
if (fd = open("./h1_1280_720_5m.mp4_mbstpos_gop1.txt", O_RDONLY) == -1) { //line caused bug
27+
//if ((fd = open("./h1_1280_720_5m.mp4_mbstpos_gop1.txt", O_RDONLY)) == -1) { //correct source code
28+
perror("open");
29+
exit(1);
30+
}
31+
printf("fd: %d\n", fd);
32+
if (stat("./h1_1280_720_5m.mp4_mbstpos_gop1.txt", &sbuf) == -1) {
33+
perror("stat");
34+
exit(1);
35+
}
36+
printf("file size: %ld", sbuf.st_size);
37+
offset = atoi(argv[1]);
38+
if (offset < 0 || offset > sbuf.st_size-1) {
39+
fprintf(stderr, "mmapdemo: offset must be in the range 0-%ld\n", sbuf.st_size-1);
40+
exit(1);
41+
}
42+
43+
data = mmap(0, sbuf.st_size, PROT_READ, MAP_SHARED, fd, 0) ;
44+
if (data == (-1)) {
45+
perror("mmap");
46+
exit(1);
47+
}
48+
49+
printf("byte at offset %d is '%c'\n", offset, data[offset]);
50+
51+
return 0;
52+
}

0 commit comments

Comments
 (0)