我的代码:
fstream fileStreamIn("text.txt", ios::in | ios::out | ios::binary);
int theSize = 100;
string theMainBuffer(theSize, '\0');
fileStreamIn.read(&theMainBuffer.front(), theSize);
theMainBuffer.resize(fileStreamIn.gcount());
//cout << theMainBuffer << endl;
fileStreamIn.close();
fileStreamIn.open("text.txt", ios::in | ios::out | ios::binary);
fileStreamIn << "blahblah";
fileStreamIn.close();
问题是什么,我怎么解决问题? 谢谢
如果不想保留前100个字节,只需创建100个长度的字符串,更改一些值并将其写入流就足够了。 不需要读取文件。
std::fstream fs("text.txt", ios_base::out | ios_base::binary);
string buffer(100, ' ');
string update="Hello";
buffer.replace(0, update.size(), update);
fs.seekp(20); // move to write position
fs.write(buffer.data(), buffer.size());
fs.close();
使用IOS::trunc作为文件打开模式。 欲知更多信息,请查看此。