提问者:小点点

C++如何使用fstream修改文件


我的代码:

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();

问题是什么,我怎么解决问题? 谢谢


共2个答案

匿名用户

如果不想保留前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作为文件打开模式。 欲知更多信息,请查看此。

相关问题


MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(c++|fstream|修改|文件)' ORDER BY qid DESC LIMIT 20
MySQL Error : Got error 'repetition-operator operand invalid' from regexp
MySQL Errno : 1139
Message : Got error 'repetition-operator operand invalid' from regexp
Need Help?