使用 std::fstream 从文件读取和附加到文件
我想知道为什么下面的代码不起作用,看起来很简单,我是否犯了错误?
其结果是:文件已创建但为空,如果我手动添加行,这些行将用此代码显示,但不会发生其他情况。
#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);
}
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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
有几件事:
当您准备好编写时,您需要
seekp()
而不是seekg()
,即现在,这里的问题是
getline ()
调用将设置流标志(特别是 eof),因此流尚未准备好进行进一步操作,您需要先清除标志!试试这个:
另外,使用 std::endl 而不是“\n”,这将在操作系统方便时触发将缓冲区刷新到文件...
Couple of things:
When you are ready to write, you need to
seekp()
rather thanseekg()
, i.e.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!try this:
Also, use std::endl rather than "\n", this will trigger a flush of the buffers to the file at the OS's convinience...