Loading from file to QList with QDataStream
-
Problem Summary: my class cMap does not load correctly (not sure if saving works either - all I know is that it generates the file). The ID of the class loads correctly, but the tiles don't.
I use QList to hold pointers to a class I made, cMap. So I have
@QList<cMap*> mapList;@I want to load and save a cMap, so I set up the following overloaded operators for the datastream:
@QDataStream &operator<<(QDataStream&, const cMap*);
QDataStream &operator>>(QDataStream&, cMap*);@cMap looks like this:
@class cMap
{
friend QDataStream &operator<<(QDataStream&, const cMap*);
friend QDataStream &operator>>(QDataStream&, cMap*);private:
int id;
int tile[maph][mapw][numLayers];
};@The QDataStream overloaded operators just print/load the id and all the tiles. Here is the code:
@QDataStream &operator<<(QDataStream& out, const cMap* map)
{
out << map->id;
for(int y=0; y<maph; y++) {
for(int x=0; x<mapw; x++) {
for(int l=0; l<numLayers; l++)
out << map->tile[y][x][l];
}
}
return out;
}QDataStream &operator>>(QDataStream& in, cMap* map)
{
in >> map->id;
for(int y=0; y<maph; y++) {
for(int x=0; x<mapw; x++) {
for(int l=0; l<numLayers; l++)
in >> map->tile[y][x][l];
}
}
return in;
}@However, only the ID is being loaded and the tiles are either corrupted data or just not loading. The tiles are all set to 0 so they're either being loaded that way or just not loaded at all because the default is 0.
This is the actual code where I save:
@//File management here
QDataStream out(&file);
out << mapList[findMap(id)];
file.close();@This is the code where I load:
@//File management here
cMap* nMap = new cMap;
in >> nMap;
mapList.append(nMap);@What am I doing wrong? I can provide more code if necessary
-
Well a single cMap should serialise to 4 + 4 * maph * mapw * numLevels bytes, so check that. I did quick check with
@
const int maph = 2;
const int mapw = 3;
const int numLayers = 4;class cMap
{
public:
cMap(int i) {
id = i;
for(int y=0; y<maph; y++) {
for(int x=0; x<mapw; x++) {
for(int l=0; l<numLayers; l++)
tile[y][x][l] = (i << 24) + (y << 16) + (x << 8) + l;
}
}
}
...
};...
cMap mapOut(5);QBuffer file; file.open(QIODevice::WriteOnly); //File management here QDataStream out(&file); out << &mapOut; file.close(); qDebug() << file.buffer().size() << file.buffer().toHex();
@
and received the expected 100 bytes. They way I filled the array is was to make the data obvious in the hex dump. Perhaps you could inspect your data to see if what is going out is what you expect.
-