#include #include #include #include #include /* * mmbackwards.c - print a file backwards using mmap rather than lseek * * idea: map the entire file into a region of memory * then traverse the region of memory from end to start using *p-- * as though it is an array. * * system calls used: * open - to get a fd for a file * stat - to get size of file * mmap - to map file to memory */ #define oops(m,x) { perror(m); exit(x); } main(int ac, char *av[]) { int fd; char *region; char *p; off_t filesize; struct stat info; int rv; off_t start_at = 0; if ( ac != 2 ){ fprintf(stderr, "usage: mmbackwards filename\n"); exit(1); } if ( stat(av[1], &info) == -1 ) oops(av[1], 2); filesize = info.st_size; if ( (fd = open(av[1],O_RDONLY)) == -1 ) oops(av[1], 3); region = (char*)mmap(NULL,filesize,PROT_READ,MAP_SHARED,fd,start_at); if ( region == (char *)MAP_FAILED ) oops("mmap",4); for( p = region + filesize - 1; p >= region ; p-- ) putchar(*p); rv = munmap(region, filesize); /* printf("\nmunmap returned %d\n", rv); */ }