File Mapping

Posted by Benjamin Meyer on October 15, 2007 · 7 comments

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.

QShare(this)

No related posts.


7 comments

1 Dave October 15, 2007 at 4:24 pm
 

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.

2 Otto October 15, 2007 at 6:06 pm
 

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

3 Benjamin Meyer October 16, 2007 at 10:38 am
 

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

4 HoussemBDIOUI October 17, 2007 at 2:04 pm
 

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?

5 CLRS530 October 18, 2007 at 11:01 am
 

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

6 Benjamin Meyer October 19, 2007 at 3:29 pm
 

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.

7 Philippe October 20, 2007 at 11:44 am
 

Great addition, it was really missing, thanks!

Comments on this entry are closed.

Previous post:

Next post: