Line 12, mmap creates a new segment in virtual memory and assigns the start virtual address to buf.
The segment's content is the file specified by argv[1], but mmap doesn't load this file into physical memory.
The file is accessed through the buf variable and is loaded using virtual memory demand paging!
Line 9: Open the file for reading,
Line 10: fstat gets the file properties (size, permissions, last time modified, etc.) in a struct.
Lines 14-18: File is mapped to memory as if in an array pointed to by buf. Print the file backwards!
1
2 int main(int argc, char* argv[])
3 {
4 char *buf;
5 int i;
6 struct stat s;
7 int fd;
8
9 fd = open(argv[1], O_RDONLY);
10 fstat(fd, &s);
11
12 buf = mmap(NULL, s.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
13
14 printf("\n\n*** File %s Backwards ***\n\n", argv[1]);
15 for(i = s.st_size - 1; i >= 0; i--) {
16 printf("%c", buf[i]);
17 }
18 printf("\n");
...
}