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();
}
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With