Creating a memory mapped file
Hi everyone!!
First of all am quite new to cpp especially under linux.
I am currently working on a small project under Linux and am having to deal with large number of data(larger than 1 GB). numerous number of operation is to be done with these data. for example: sorting, searching, comparing ... etc. so in order to perform all these operations it is important that these data are in the memory...
in order to deal with such a large amount of data am thinking of using a memory mapped file..
can anyone help me or guide me in the steps of creating a memory mapped file?
Please help ..
Thanking in advance
Re: Creating a memory mapped file
Your basic approach seems flawed.
Memory Mapped Files are typically used when an existing implementation (or other requirement) DICTATES that the operation must be performed on "files", and you are looking for a faster media than disk.
A memory mapped solution will never be smaller or faster than an optimal object based implementation.
So, before getting into the "how" can you explain the "why?"
Re: Creating a memory mapped file
Check out this short tutorial that explains how you would memory map a file : http://www.ecst.csuchico.edu/~beej/guide/ipc/mmap.html
Re: Creating a memory mapped file
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <errno.h>
int main(int argc, char *argv[])
{
int fd, offset;
char *data;
struct stat sbuf;
if (argc != 2) {
fprintf(stderr, "usage: mmapdemo offset\n");
exit(1);
}
if ((fd = open("mmapdemo.c", O_RDONLY)) == -1) {
perror("open");
exit(1);
}
if (stat("mmapdemo.c", &sbuf) == -1) {
perror("stat");
exit(1);
}
offset = atoi(argv[1]);
if (offset < 0 || offset > sbuf.st_size-1) {
fprintf(stderr, "mmapdemo: offset must be in the range 0-%d\n", \
sbuf.st_size-1);
exit(1);
}
if ((data = mmap((caddr_t)0, sbuf.st_size, PROT_READ, MAP_SHARED, \
fd, 0)) == (caddr_t)(-1)) {
perror("mmap");
exit(1);
}
printf("byte at offset %d is '%c'\n", offset, data[offset]);
return 0;
}