File Mapping

Published Monday October 15th, 2007
7 Comments on File Mapping
Posted in Qt

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.

Do you like this? Share it
Share on LinkedInGoogle+Share on FacebookTweet about this on Twitter

Posted in Qt

7 comments

Dave says:

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.

Otto says:

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

HoussemBDIOUI says:

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?

CLRS530 says:

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.

Philippe says:

Great addition, it was really missing, thanks!

Commenting closed.

Get started today with Qt Download now