小编osm*_*alp的帖子

fseek() 函数中的零偏移量与 SEEK_CUR 有什么用?

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);
}
Run Code Online (Sandbox Code Playgroud)

使用上面的代码,我尝试将二进制文件中每个产品的价格加倍,其中每个记录都是 Product 结构的实例。当我运行此代码时,它正确更新了文件中的所有价格。

据我所知,fread自动将文件指针移动到下一条记录。使用第一个fseek,代码将文件指针移回到记录的开头。然后它使用 更新它fwritefwrite自动将文件指针移动到下一条记录。在while循环中,fread应该继续读取下一条记录,以此类推。

这里似乎fseek(file, 0, SEEK_CUR);没有必要。但是,如果我删除它,代码就会进入无限循环。我不明白为什么会发生这种情况。

我尝试使用 观察文件指针的值ftell。但我没有看到它的值有任何变化fseek(file, 0, SEEK_CUR);

c io file fseek language-lawyer

49
推荐指数
2
解决办法
2486
查看次数

标签 统计

c ×1

file ×1

fseek ×1

io ×1

language-lawyer ×1