C++|读入文件内容、查找替换后输出到另一个文件-如何打开dat文件

C++|读入文件内容、查找替换后输出到另一个文件-如何打开dat文件

有文件cad.dat,其内容如下:

C is one of the world's most modern

programming languages. There is no

language as versatile as C, and C

is fun to use.

现在的任务是,读取以上文件的内容,并将其中的字符“C“替换为“C++“并写入文件。

#include <fstream>
#include <iostream>
#include <cstdlib>
using namespace std;
void addPlusPlus(ifstream& inStream, ofstream& outStream);
int main( )
{
ifstream fin;
ofstream fout;
cout << "Begin editing files.\n";
fin.open("cad.dat");
if (fin.fail( ))
{
cout << "Input file opening failed.\n";
exit(1);
}
fout.open("cplusad.dat");
if (fout.fail( ))
{
cout << "Output file opening failed.\n";
exit(1);
}
addPlusPlus(fin, fout);
fin.close( );
fout.close( );
cout << "End of editing files.\n";
return 0;
}
void addPlusPlus(ifstream& inStream, ofstream& outStream)
{
char next;
inStream.get(next);//从文件读取一个字符给next
while (! inStream.eof( ))
{
if (next == 'C')
outStream << "C++";//输出字面常量给文件
else
outStream << next;//输出变量next值给文件
inStream.get(next);
}
}

以上程序运行后,会在当前目录下自动新建一文件cplusad.dat,其内容如下:

C++ is one of the world's most modern
programming languages. There is no
language as versatile as C++, and C++
is fun to use.

-End-

推荐阅读