这是一个初学者的问题。我试图在文本文件中找到一个字符串并将其替换回同一个文件。以下代码可以很好地将文件内容收集到缓冲区中并替换字符串。但是当我尝试将数据保留回同一个文件时,它充满了一些垃圾字符。请让我知道我做错了什么?
#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.