C++ seekp()在二进制模式下替换部分文件时出现问题
我在以二进制模式替换文件的一部分时遇到了一些问题。由于某些原因,我的seekp()行没有将文件指针放置在所需的位置。现在,它将新内容附加到文件的末尾,而不是替换所需的部分C++ seekp()在二进制模式下替换部分文件时出现问题,c++,fstream,C++,Fstream,我在以二进制模式替换文件的一部分时遇到了一些问题。由于某些原因,我的seekp()行没有将文件指针放置在所需的位置。现在,它将新内容附加到文件的末尾,而不是替换所需的部分 long int pos; bool found = false; fstream file(fileName, ios::binary|ios::out|ios::in); file.read(reinterpret_cast<char *>(&record), sizeof(Person)); wh
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();
long int pos;
bool-found=false;
fstream文件(文件名,ios::binary | ios::out | ios::in);
file.read(reinterpret_cast(&record),sizeof(Person));
而(!file.eof())
{
if(record.getNumber()==number){
pos=file.tellg();
发现=真;
打破
}
//记录对象在此处更新
file.seekp(pos,ios::beg);//这不是将文件指针放在所需的位置
file.write(reinterpret_cast(&record),sizeof(Person));
cout我不知道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) );
}
#包括
#包括
使用名称空间std;
结构P{
int n;
};
int main(){
fstream文件(“afile.dat”,ios::binary | ios::out | ios::in);
P;
p、 n=1;
write((char*)&p,sizeof(p));
p、 n=2;
int pos=0;
seekp(pos,ios::beg);
write((char*)&p,sizeof(p));
}
在这里,您既不更新号码也不更新记录,所以基本上您要遍历所有文件并在“某些”位置写入(pos未初始化)
Neil Butterworth是对的(在我打8的时候贴的))看起来你省略了smth
while (!file.eof())
{
if (record.getNumber() == number) {
pos=file.tellg();
found = true;
break;
}