C++ 简单的文件操作


#include 
#include 
#include 

using namespace std;


// 输出的时候把文件中的 C 换成 C++
void addPlusPlus(ifstream& inStream, ofstream& outStream)
{
    char next;

	inStream.get(next);
	while (!inStream.eof()) {
		if (next == 'C') {
			outStream << "C++";
		}
		else {
			outStream << next;
		}

		inStream.get(next);
	}
}

int main()
{
	ifstream fin;
	ofstream fout;

	cout << "开始编辑文件\n";
	fin.open("cad.dat");
	if (fin.fail()) {
		cout << "文件打开不成功\n";
		exit(1);
	}

	fout.open("cplusad.dat");
	if (fout.fail()) {
		cout << "文件打开不成功\n";
		exit(1);
	}

	addPlusPlus(fin, fout);

	fin.close();
	fout.close();

	cout << "文件编辑完成\n";

	return 0;
}

输出:

cad.dat

cplusad.dat




参考:

《C++入门经典 10版》 P248