Skip to content

Instantly share code, notes, and snippets.

@benwills
Created December 27, 2014 04:55
Show Gist options
  • Select an option

  • Save benwills/b2c73f130d2988746678 to your computer and use it in GitHub Desktop.

Select an option

Save benwills/b2c73f130d2988746678 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <unistd.h> //lseek, write, close
#include <stdlib.h> //exit
#include <fcntl.h> //open
#include <sys/mman.h>
#define Mapmalloc(number, type, filename, fd) load_mmap(filename, &(fd), (number)*sizeof(type), 'y')
#define Mapload(number, type, filename, fd) load_mmap(filename, &(fd), (number)*sizeof(type), 'n')
#define Mapfree(number, type, fd, pointer) releasemmap(pointer, (number)*sizeof(type), fd)
#define Stopifnot(assertion, ...) if (!(assertion)){printf(__VA_ARGS__); exit(1);}
void *load_mmap(char *filename, int *fd, size_t size, char make_room) {
*fd = open(filename,
make_room=='y' ? O_RDWR | O_CREAT | O_TRUNC : O_RDWR,
(mode_t)0600);
Stopifnot(*fd != -1, "Error opening file");
if (make_room=='y'){ // Stretch the file size to the size of the (mmapped) array
int result = lseek(*fd, size-1, SEEK_SET);
Stopifnot(result != -1, "Error calling lseek() to stretch the file");
result = write(*fd, "", 1);
Stopifnot (result == 1, "Error writing last byte of the file");
}
void *map = mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, *fd, 0);
Stopifnot (map != MAP_FAILED, "Error mmapping the file");
return map;
}
void releasemmap(void *map, size_t size, int fd){
Stopifnot(munmap(map, size) != -1, "Error un-mmapping the file");
close(fd);
}
int main(int argc, char *argv[]) {
int fd;
long int N=1e5+6;
int *map = Mapmalloc(N, int, "mmapped.bin", fd);
for (long int i = 0; i <N; ++i) map[i] = i; //you can't tell it's on disk.
Mapfree(N, int, fd, map);
//Now reopen and do some counting.
int *readme = Mapload(N, int, "mmapped.bin", fd);
long long int oddsum=0;
for (long int i = 0; i <N; ++i) if (readme[i]%2) oddsum += i;
printf("The sum of odd numbers up to %li: %lli\n", N, oddsum);
Mapfree(N, int, fd, readme);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment