使用std :: fstream从文件读取和添加文件 [英] Reading and appending from/to a file with std::fstream
问题描述
我想知道为什么下面的代码不起作用,看起来很简单,我犯了一个错误吗?
这样做的结果是:文件已创建但为空,如果我手动添加行,则这些行将与该代码一起显示,但是没有其他反应.
I'm wondering why the following piece of code doesn't work, looks pretty straight-forward, am I making a mistake?
The result of this is: file created but empty, if I manually add lines those lines are showed with this code, but nothing else happens.
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main(){
fstream mfile("text.txt", ios_base::in | ios_base::out | ios_base::app);
mfile.seekg(ios_base::beg);
string line;
while( getline(mfile,line) ){
std::cout << line << "\n";
}
mfile.seekg(ios_base::end);
mfile << "Line 1\n";
mfile << "Line 2\n";
mfile << "---------------------------------\n";
mfile.seekg(ios_base::beg);
while( getline(mfile,line) ){
std::cout << line << "\n";
}
mfile.seekg(ios_base::end);
}
推荐答案
事物的结合:
准备好写时,您需要seekp()
而不是seekg()
,即
When you are ready to write, you need to seekp()
rather than seekg()
, i.e.
mfile.seekp(ios_base::end);
现在,这里的问题是getline()
调用将设置流标志(特别是eof),因此,该流还没有准备好进行进一步的操作,您需要先清除这些标志!
Now, the problem here is that the getline()
calls will set the stream flags (specifically eof), and as a result the stream is not ready for further operations, you need to clear the flags first!
尝试一下:
string line;
mfile.seekg(ios_base::beg);
while( getline(mfile,line) ){
std::cout << line << endl;
}
mfile.seekp(ios_base::end); // seekp
mfile.clear(); // clear any flags
mfile << "Line 1" << endl; // now we're good
mfile << "Line 2" << endl;
mfile << "---------------------------------" << endl;
mfile.seekg(ios_base::beg);
while( getline(mfile,line) ){
std::cout << line << endl;
}
另外,使用std :: endl而不是"\ n",这将在操作系统方便时触发将缓冲区刷新到文件...
Also, use std::endl rather than "\n", this will trigger a flush of the buffers to the file at the OS's convinience...
这篇关于使用std :: fstream从文件读取和添加文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!