This is a beginner question. I am trying to find a string in text file and replace it back to the same file. Following code works fine collecting contents of file into buffer and replace the string . But when i try to keep the data back to same file, it is filled with some junk character. Please let me know what I am doing wrong ?
#include <iostream> #include <fstream> using namespace std; const char *fileName = "Test.dat"; int main () { // This is where we'll put the stuff we read from file char buffer[ 100 ]; ifstream finout(fileName, ios_base::in | ios_base::out | ios_base::binary); if(!finout.is_open()) { cout << "Can not open file " << endl; return(1); } while (finout.getline(buffer, sizeof(buffer)) { string g( buffer ); string search = "am"; string replace = "was"; long j; if ( (j = g.find(str2)) != string::npos) { g.replace(g.find(str2), str2.length(), "str"); finout.write((char *) &g, sizeof(g)); //This won't work } cout << g << "\n"; finout.close(); return 0; } My Test.dat file contain following information:
Hello, How are you? I am fine.