C++ program to find and replace a string in file
<p>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 ?</p>

<pre><code>#include &lt;iostream&gt;
#include &lt;fstream&gt;
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 &lt;&lt; "Can not open file " &lt;&lt; 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 *) &amp;g, sizeof(g)); //This won't work 

    }

cout &lt;&lt; g &lt;&lt; "\n";
finout.close();
return 0;
}
</code></pre>

<p>My Test.dat file contain following information:</p>

<pre><code>Hello, How are you?
I am fine.
</code></pre>
