Reputation: 167
please let me know how a pointer ( in C / C++ programming language ) can reference to a segment in hard disk, a storage of say upto 1 GB.
In more details i am going to write the signature of a function which will take a pointer as argument and that should point to a segment in hard disk, which can hold upto 1 GB space, instead of passing the pointer pointing to the address, which holds the same amount of storage, on heap I want it to point to hard disk segment. system is Linux, programming languages both C & C++.
Upvotes: 0
Views: 2487
Reputation: 22552
You have to map the data into your virtual address space.
open your file or block device (e.g. /dev/sda
) with open(2)
and pass the file descriptor here:
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/mman.h>
void * map_file_descriptr(int fd) {
struct stat file_stat;
if (fstat(fd, &file_stat)) {
perror("fstat");
// do something on error
return NULL;
}
void * data = mmap(
NULL // place the the VM segment anywhere in the process virtual address space
, file_stat.st_size // file size
// For read-only:
, PROT_READ
, MAP_PRIVATE
// for read-write
/*
, PROT_READ | PROT_WRITE
, MAP_SHARED
*/
, fd // file which belongs to this file descriptor
, 0 // from the beginning
);
if (data == MAP_FAILED) {
perror("mmap");
// you most likely are out of memory to allocate the VM table
// this very rarely happens
return NULL;
}
return data;
}
If you mapped the file with MAP_SHARED
for read-write access then you need to msync(2)
it to flush the updates to disk.
Careful: Mapping a file with MAP_PRIVATE
has undefined behaviour if the file is modified by another process after the mapping. Also any mapping will result in undefined behaviour if the file size is changed after the mapping.
Note: MAP_PRIVATE
mappings with PROT_WRITE
can be written to, but the changes will not be written back to the file when the mapping is removed, those mappings cannot be synched either.
Upvotes: 4
Reputation: 74088
You can look into mmap
. This allows to map files into your main memory.
Upvotes: 5