我在用二進制模式替換文件的一部分時遇到了一些麻煩。出於某種原因,我的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();
我做錯了什麼?
非常感謝。