使用fseek读取和写入文件,读取错误数据

时间:2012-08-08 17:39:11

标签: c file-io fseek

我实际上要做的是创建一个2D数组,但是在一个文件中而不是在主内存中。

为了跳转到这个文件我使用fseek然后fread将我需要的内容返回到我正在使用的结构中,问题是当我从loadTile()中的文件中读取时结构gameTile8File gtf充满了似乎是垃圾数据。

请注意,在写入和读取之间,文件永远不会关闭或刷新,不要认为这应该有所作为。该文件是二进制文件,始终使用选项"r+b"打开。

我正在检查fseek()fread()fwrite()上的返回值,所有人都说没有问题。

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(&gtf, 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(&gtf, 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(&gtf, sizeof(gameTile8File), 1, file1) != 1)
    {
        cout << "read failed! 01\n";
    }
    //then load it
    gtf.load(gt, file1, file2);
}

1 个答案:

答案 0 :(得分:1)

我认为你的问题是fseek()采用字节偏移量。您需要将偏移量乘以sizeof(gameTile8File)

fseek(file1, sizeof(gameTile8File)*(y * worldTileKey::gameWorldSizeX*worldTile::worldTileCountX + x), SEEK_SET))

我不清楚你使用worldTileKey::gameWorldSizeX*worldTile::worldTileCountX。您存储在文件worldTileKey::gameWorldSizeX*worldTile::worldTileCountX中的网格是否为瓷砖宽?