0

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. 

3 Answers 3

1
  • When you are read/write as a text file, do not open it by ios_base::binary
  • You put finout.close(); inside your reading loop, so it just work for one line.
  • When you are reading/writing a file as a text, use text stream methods and operators.
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks !! It worked. I wrote altered contents into a temporary file. And added following code to copy the temp file contents to original after while loop. finout << fout.rdbuf; if(!fout.eof()) std::cerr << "reading from file failed\n"; if(!finout.good()) std::cerr << "writing to file failed\n"; now fout points to temp file. But everytime it throws error that reading from a file is failed. Did i miss anything here ?
0

You are trying to read the size of your string with the sizeof() operator.

This wont work, because it is a keyword, that gives you the non-dynamic size of the object or type.

You should use g.size() to access the string size!

But on the first place, you can handle the stream handle your bug:

finout << g; 

will do the job.

Comments

0

First, you want to both read and write a file, so use fstream not ifstream. Second, you have a text file, so don't use ios_base::binary Third (char*) &g where g is std::string doesn't work, use g.c_str() instead. (simply write finout << g;

Now you can start thinking of the implmentation...

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.