【发布时间】:2011-11-28 11:41:51
【问题描述】:
我有一个二进制文件 (test.bin),其中有 2 个无符号整数值,分别为 1000 和 4000。 使用下面的代码,我想用第一个写入函数将第一个数字更改为 5000,然后我想读取第二个数字并用 4000-2000 = 2000 重写它。 但是,程序将 1000 更改为 5000,但没有将 4000 更改为 2000。即使我使用 file.flush() 或 file.sync(),它也没有任何效果。 有趣的是,当我输入 file.tellg() 或 file.tellp() 时,它可以按我的意愿工作。 (我偶然发现的) 这在 Linux 和 Windows 上都会发生。在 Linux 上,我尝试用 g++ 编译它。 sizeof(unsigned int)=4 并且我确信程序可以打开 test.bin。
#include <fstream>
#include <iostream>
using namespace std;
int main(){
fstream file;
unsigned int data, buffer;
data=5000;
file.open("test.bin", ios::binary | ios::in | ios::out);
file.write((char*)&data,4); // will change first number to 5000
// file.flush(); // Nothing changes if I delete comment signs.
// file.tellp(); // Program works correctly if I uncomment this.
// file.tellg(); // Program works correctly if I uncomment this.
file.read((char*)&buffer, 4); // position pointer should be at the beginning of the 2nd number
file.seekp(-4, ios::cur); // Since internal pointer is at the end of the file after the read(), I manually put it back to the beginning of the 2nd number.
buffer-=2000;
file.write((char*)&buffer,4); // Now, it should rewrite 2nd number with 2000.
file.close();
return 0;
}
【问题讨论】:
-
我不明白你为什么要搜索,读完后 fp 应该在第二个数字的开头。
-
没错,我自己没有找到做 seekp 的解释。它应该正好在第二个数字的开头,但是当我执行它时它不起作用。但是,当我取消注释 seekg 时,它起作用了!我不知道为什么……很奇怪。