Skip to content

Instantly share code, notes, and snippets.

@alandipert
Created June 12, 2009 12:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alandipert/128616 to your computer and use it in GitHub Desktop.
Save alandipert/128616 to your computer and use it in GitHub Desktop.
mmap character reading example
#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