开发者

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

开发者 https://www.devze.com 2023-01-23 19:28 出处:网络
I\'m wondering why the following piece of code doesn\'t work, looks pretty straight-forward, am I making a mistake?

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_ba开发者_如何学运维se::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);

}


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...

0

精彩评论

暂无评论...
验证码 换一张
取 消