Created
June 12, 2009 12:56
-
-
Save alandipert/128616 to your computer and use it in GitHub Desktop.
mmap character reading example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <fcntl.h> | |
#include <stdlib.h> | |
#include <unistd.h> | |
#include <sys/types.h> | |
#include <sys/mman.h> | |
#include <sys/stat.h> | |
//takes a filename as 1st argument | |
//opens it, and mmaps the whole thing. | |
//demonstrates the use of mmap for character | |
//reading | |
int main(int argc, char **argv) { | |
int i, fd, pagesize; | |
char *data; | |
struct stat file_status; | |
unsigned long int bytes_read, bytes_left, to_read; | |
fd = open(argv[1], O_RDONLY); | |
fstat(fd, &file_status); | |
pagesize = getpagesize(); | |
bytes_left = file_status.st_size; | |
while(bytes_left > 0) { | |
if(bytes_left > pagesize) { | |
to_read = pagesize; | |
} else { | |
to_read = bytes_left; | |
} | |
data = mmap((caddr_t)0, to_read, PROT_READ, MAP_SHARED, fd, bytes_read); | |
for(i = 0; i < to_read; i++) { | |
/*putchar(data[i]);*/ | |
} | |
munmap(data, to_read); | |
bytes_read += to_read; | |
bytes_left -= to_read; | |
} | |
return EXIT_SUCCESS; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment