Jack M
Jack M

Reputation: 6025

Trivial C++ program not writing to file

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

Upvotes: 4

Views: 253

Answers (1)

Nemo
Nemo

Reputation: 71605

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

Upvotes: 8

Related Questions