これは初心者の質問です。テキストファイルで文字列を見つけて、同じファイルに置き換えようとしています。次のコードは、ファイルの内容をバッファに収集して正常に機能し、文字列を置き換えます。しかし、データを同じファイルに戻そうとすると、ジャンク文字でいっぱいになります。私が間違っていることを教えてください。
#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;
}
私の Test.dat ファイルには次の情報が含まれています。
Hello, How are you?
I am fine.