while (fread(&product, sizeof(Product), 1, file) == 1) {
product.price *= 2.0;
fseek(file, -sizeof(Product), SEEK_CUR);
fwrite(&product, sizeof(Product), 1, file);
fseek(file, 0, SEEK_CUR);
}
使用上面的代码,我尝试将二进制文件中每个产品的价格加倍,其中每个记录都是 Product 结构的实例。当我运行此代码时,它正确更新了文件中的所有价格。
据我所知,fread
自动将文件指针移动到下一条记录。使用第一个fseek
,代码将文件指针移回到记录的开头。然后它使用更新它fwrite
. fwrite
自动将文件指针移动到下一条记录。在 while 循环中,fread
应继续读取下一条记录,依此类推。
看起来fseek(file, 0, SEEK_CUR);
这里是不必要的。但是,如果我删除它,代码就会进入无限循环。我不明白为什么会发生这种情况。
我尝试使用观察文件指针的值ftell
。但我没有看到它的值有任何变化fseek(file, 0, SEEK_CUR);
.