I am experimenting with mmap in following way, but I can not understand if it is correct:
#include <fcntl.h> // open
#include <unistd.h> // ftuncate
#include <sys/mman.h> // mmap
#include <cstdlib>
#include <cstring>
#include <cstdio>
int main(){
off_t const size = 5 * 1024 * 1024;
const char *filename = "testfile";
int fd = open(filename, O_RDWR | O_TRUNC | O_CREAT, 0644);
ftruncate(fd, size);
char *mem = (char *) mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, /* offset */ 0);
const char *msg = "Hello";
memcpy(&mem[100], msg, strlen(msg));
memcpy(&mem[200], msg, strlen(msg));
memcpy(&mem[4 * 1024 * 1024], msg, strlen(msg));
}
As long I understand, ftruncate
create a file with hole. Isn't this a problem for mmap
later?
Will this work on 10 GB file on 64 bit system?
On Linux shall I use fallocate(fd, FALLOC_FL_ZERO_RANGE, 0, 8 * size)
or there is no significant difference in speed?
Holes in files have no effect on any normal file operations, they're just an optimization in the way the file is stored on disk. As far as any operations like reading, seeking, memory mapping, etc. are concerned, it's just a long series of zero bytes. The filesystem driver takes care of turning the hole into a block of zeroes when reading the relevant pages into memory.
For the difference between fallocate()
and ftruncate()
, see what's the difference between fallocate and ftruncate