PDA

View Full Version : Mapping a file to a struct



DiamonDogX
31st July 2009, 14:39
I am aware of the QFile::map() function, which maps the bytes of a file into memory. I am wondering how to map the bytes of a file to a struct I have defined, being able to read/write to the file using the struct (in memory). Thanks!

TMan
31st July 2009, 14:47
Sounds like you want a union. Or well, maybe you don't *want* a union, but at least it sound like that's wat you want to do. Or just typecast your memory to the struct?

Or perhaps explain the problem better ;)

shentian
31st July 2009, 14:56
I'd do something like this:



struct MyStruct {
// ...;
};

QFile file;
// ...
MyStruct* myStruct = reinterpret_cast<MyStruct*>(file.map(offset, sizeof(MyStruct)));



But to access binary data in a file, I'd rather use QDataStream.

DiamonDogX
31st July 2009, 15:57
Actually, what I'm currently using is QDataStream and seeking to certain offsets in the file that correspond to offsets of data members in my struct (by using the offsetof macro). Why do you say using QDataStream would be better in this case? Thanks.