Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trivial C++ program not writing to file

Tags:

c++

These lines are the sole contents of main():

fstream file = fstream("test.txt", ios_base::in | ios_base::out);
string word;
while (file >> word) { cout << word + " "; }
file.seekp(ios::beg);
file << "testing";
file.close();

The program correctly outputs the contents of the file (which are "the angry dog"), but when I open the file afterwards, it still just says "the angry dog", not "testingry dog" like I would expect it to.

Full program:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
    fstream file = fstream("test.txt", ios_base::in | ios_base::out);
    string word;
    while (file >> word) { cout << word + " "; }
    file.seekp(ios::beg);
    file << "testing";
    file.close();
}
like image 286
Jack M Avatar asked Feb 19 '23 13:02

Jack M


1 Answers

You have two bugs in your code.

First, iostream has no copy constructor, so (strictly speaking) you cannot initialize file the way you do.

Second, once you run off the end of the file, eofbit is set and you need to clear that flag before you can use the stream again.

fstream file("test.txt", ios_base::in | ios_base::out);
string word;
while (file >> word) { cout << word + " "; }
file.clear();
file.seekp(ios::beg);
file << "testing";
file.close();
like image 108
Nemo Avatar answered Feb 27 '23 03:02

Nemo