Traditionally when you wanted to map a file into memory on Unix this was done using mmap and on Windows with CreateFileMapping. Continuing the tradition of simple, consistent API’s, in 4.4 QFile will have two new functions: map() and unmap() that provide the ability to map files into memory.
An quick example:
QFile file("foo");
file.open(QFile::ReadOnly);
uchar *memory = file.map(0, file.size());
if (memory) {
// have some fun with the data
file.unmap();
}
You can check out more in the
map and unmap documentation.
No related posts.
7 comments
What’s the file size limit? In Windows, the default behavior limits you to 512Mb, and Linux has a similar limitation, unless a special API is used.
Does this take any file systems into account? We see big differences between local disk, NFS mounts or other more exotic file systems.
I would realy like to use this feature
Dave: The code doesn’t change the limit so it is whatever the OS gives is the limit (I think win2k has higher then 512, at least I have used 800+). I added a way for to add Options to the mapping so we can add platform specific options as they are requested.
Otto: It uses mmap behind the scene and doesn’t do any explicit checking for what filesystem it is on, so if your file is on a NFS mount you might not get the best performance.
-Benjamin Meyer
Interesting… Maybe this is a stupid question, but how is it ensured that one cannot write into the memory
when the file has been opened as QFile::ReadOnly?
Why do you shouldn´t be allowed to write in memory if a file is opened as readonly? Read only means the file must not be changed. But it don´t means you cannot write it anywhere
HoussemBDIOUI: If you open a file in readOnly and then map it [in readonly] and then try to change it I believe that you will cause a segfault. Same thing that happens when you try to write to a shared memory that is attached readonly.
Great addition, it was really missing, thanks!
Comments on this entry are closed.