What I’m essentially trying to do is to create a 2D array but one that is in a file rather than in main memory.
In order to jump around this file i’m using fseek then fread to return what I need into the structures i’m using, the problem being that when I read from the file in loadTile() the structure gameTile8File gtf is full of what appears to be junk data.
Note that between the write and the read the file is never closed or flushed, don’t think that should make a difference. The file is binary and always opened with options "r+b".
I’m checking the return values on fseek(), fread() and fwrite() and all are saying there isn’t a problem.
void saveTile(gameTile8& gt, unsigned int x, unsigned int y, bool newFile)
{
//the given coordinates are in world space
//first load the old coordinates (needed so that correct movements in file 2 are made)
if(fseek(file1, (y * worldTileKey::gameWorldSizeX*worldTile::worldTileCountX) + x, SEEK_SET))
{
cout << "fseek failed! 01\n";
}
gameTile8File gtf;
fread(>f, sizeof(gameTile8File), 1, file1);
//convert a gameTile8 to a gameTile8File
gtf.save(gt, file2, newFile);
//once all movements are done then save the tile
if(fseek(file1, (y * worldTileKey::gameWorldSizeX*worldTile::worldTileCountX) + x, SEEK_SET))
{
cout << "fseek failed! 01\n";
}
if(fwrite(>f, sizeof(gameTile8File), 1, file1) != 1)
{
cout << "fwrite failed! 01\n";
}
}
void loadTile(gameTile8& gt, unsigned int x, unsigned int y)
{
//the given coordinates are in world space
//seek to the given spot load it
if(fseek(file1, (y * worldTileKey::gameWorldSizeX*worldTile::worldTileCountX) + x, SEEK_SET))
{
cout << "fseek failed! 01\n";
}
gameTile8File gtf;
//read in the tile
if(fread(>f, sizeof(gameTile8File), 1, file1) != 1)
{
cout << "read failed! 01\n";
}
//then load it
gtf.load(gt, file1, file2);
}
I think your problem is that
fseek()takes an offset in bytes. You need to multiply your offset by thesizeof(gameTile8File):I’m not clear on your use of
worldTileKey::gameWorldSizeX*worldTile::worldTileCountX. Is the grid you’re storing in the fileworldTileKey::gameWorldSizeX*worldTile::worldTileCountXtiles wide?