Reading and appending from/to a file with std::fstream

≯℡__Kan透↙ 提交于 2019-12-11 17:26:19

问题


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

}

回答1:


Couple of things:

When you are ready to write, you need to seekp() rather than seekg(), i.e.

mfile.seekp(ios_base::end);

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:

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;
}

Also, use std::endl rather than "\n", this will trigger a flush of the buffers to the file at the OS's convinience...



来源:https://stackoverflow.com/questions/4100880/reading-and-appending-from-to-a-file-with-stdfstream

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!