2
votes

In test.txt file i have one word "aa". I want to replace it with "aa1". However, the program below does not change the file. What's wrong?

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

int main()
{
    fstream iofile("test.txt",ios_base::in|ios_base::app);
    if (!iofile)
            cerr << "Unable to open file!";

    string word;
    iofile >> word;
    word.push_back('1');
    iofile.seekg(0);
    iofile << word;  
}
1

1 Answers

3
votes

You realize that ios_base::app is causing you to append to the end of the file no matter where you try to seek for write, right? Maybe you meant to specific ios_base::out instead?

Also, for writes, it's seekp() not seekg().