arkhy
arkhy

Reputation: 447

Cant write after reading to file stream with in and out options

I have a problem with file streams. What i need is to open file, read it, and then write some values on it. So this is what i have now

        std::string filename;
    std::fstream save_file;
    save_file.open(SAVED_HASH, std::fstream::in | std::fstream::out | std::fstream::binary);
    while (save_file >> filename);
    save_file.seekg(save_file.beg);
    save_file << " more lorem ipsum";
    save_file.close();

and when i try to run it, all i got is just an empty file. But it works if i remove 4th line. What is wrong with this code, why i can't read file, and then write

Upvotes: 0

Views: 449

Answers (1)

Abhishek Bansal
Abhishek Bansal

Reputation: 12715

One error that I can spot is that after

while (save_file >> filename); 

you need to clear the error flag.

save_file.clear();

Also, IMO you need to use seekp instead of seekg as you want to 'write' at the position.

See this link for an example http://www.cplusplus.com/reference/ostream/ostream/seekp/?kw=seekp

Upvotes: 1

Related Questions