I'm afraid you might have to rewrite the entire file. Here is how you could do it:
#include <iostream> #include <fstream> using namespace std; int main() { string strReplace = "HELLO"; string strNew = "GOODBYE"; ifstream filein("filein.txt"); //File to read from ofstream fileout("fileout.txt"); //Temporary file if(!filein || !fileout) { cout << "Error opening files!" << endl; return 1; } string strTemp; //bool found = false; while(filein >> strTemp) { if(strTemp == strReplace){ strTemp = strNew; //found = true; } strTemp += "\n"; fileout << strTemp; //if(found) break; } return 0; }
Input file:
ONE TWO THREE HELLO SEVEN
Output file:
ONE TWO THREE GOODBYE SEVEN
Just uncomment the commented lines if you want this to replace the first event. In addition, I forgot at the end to add code that removes filein.txt and renames fileout.txt to filein.txt.
Anton source share