我有一個二進制文件(test.bin),它有兩個unsigned int值,分別是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。對C++文件的後續讀寫操作
#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;
}
我不明白你爲什麼seekp,讀的FP後應該是在第二號的開頭。 – Bond
的確,我,我自己找不到解釋來做seekp。它應該正好在第二個數字的開頭,但是當我執行它時,它不起作用。但是,當我取消註釋seekg它的作品!我不知道爲什麼......很奇怪。 – atakan