gpt4 book ai didi

c - 使用fseek读写文件,读取数据错误

转载 作者:行者123 更新时间:2023-11-30 15:55:42 26 4
gpt4 key购买 nike

我本质上想做的是创建一个二维数组,但它位于文件中而不是主内存中。

为了跳转这个文件,我使用 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);
}

最佳答案

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

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

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

关于c - 使用fseek读写文件,读取数据错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11870093/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com