2009-05-03 30 views
0

我在用二進制模式替換文件的一部分時遇到了一些麻煩。出於某種原因,我的seekp()行不會將文件指針放在所需的位置。現在它將新內容附加到文件末尾,而不是替換所需的部分。用seekp()替換二進制模式下文件的部分時遇到的問題

long int pos; 
bool found = false; 
fstream file(fileName, ios::binary|ios::out|ios::in); 

file.read(reinterpret_cast<char *>(&record), sizeof(Person)); 

while (!file.eof()) 
{ 
    if (record.getNumber() == number) { 
     pos=file.tellg(); 
     found = true; 
     break; 
} 

// the record object is updated here 

file.seekp(pos, ios::beg); //this is not placing the file pointer at the desired place 
file.write(reinterpret_cast<const char *>(&record), sizeof(Person)); 
cout << "Record updated." << endl; 
file.close(); 

我做錯了什麼?

非常感謝。

回答

1

我不明白你的while()循環是如何工作的。一般來說,您不應該測試eof(),而應該測試讀取操作是否正常。

下面的代碼將記錄到文件(必須存在),然後將其覆蓋:

#include <iostream> 
#include <fstream> 
using namespace std; 

struct P { 
    int n; 
}; 

int main() { 
    fstream file("afile.dat" , ios::binary|ios::out|ios::in); 
    P p; 
    p.n = 1; 
    file.write((char*)&p, sizeof(p)); 
    p.n = 2; 
    int pos = 0; 
    file.seekp(pos, ios::beg); 
    file.write((char*)&p, sizeof(p)); 
} 
0
while (!file.eof()) 
{ 
    if (record.getNumber() == number) { 
     pos=file.tellg(); 
     found = true; 
     break; 
} 

在這裏 - 你`重新不更新數也創紀錄的 - 所以基本上你去通過所有文件,並在「一些」位置寫(POS並不inited)

和尼爾北海是正確的(發佈而我輸入8))好像你省略不便