c++ 简单文本替换

#include 
#include 
#include 
using namespace std;


int main(int argc, char** argv)
{
	if (argc < 5)
	{
		cout << "usage: {executable} {from_file_name} {to_file_name} {from_str(such as 30001)} {to_str(such as 30013)}";
		return -1;
	}

	string strFromFileName = argv[1];
	string strToFileName = argv[2];

	const string strFrom = argv[3];
	const string strTo = argv[4];

	ifstream ifs;
	ifs.open(strFromFileName, ios::in);
	ofstream ofs;
	ofs.open(strToFileName, ios::out | ios::trunc);
#define MAX_LNE_LEN 2048
	char szLine[MAX_LNE_LEN + 1];
	while (ifs.good() && !ifs.eof())
	{
		memset(szLine, 0, MAX_LNE_LEN);
		ifs.getline(szLine, MAX_LNE_LEN);
		szLine[MAX_LNE_LEN] = '\0';
		string strTmp = szLine;
		auto posTmp = strTmp.find(strFrom);
		if (posTmp != string::npos)
		{
			while (posTmp != string::npos)
			{
				string strPre = strTmp.substr(0, posTmp);
				ofs.write(strPre.c_str(), strPre.size());
				ofs.write(strTo.c_str(), strTo.size());
				strTmp = strTmp.substr(posTmp + strlen(strFrom.c_str()));
				posTmp = strTmp.find(strFrom);
			}
			ofs.write(strTmp.c_str(), strTmp.size());
		}
		else
		{
			auto nLen = strlen(szLine);
			ofs.write(szLine, nLen);
		}
		ofs.write("\n", 1);
	}

	ofs.flush();
	ifs.close();
	ofs.close();

	return 0;
}


replace.bat:

simplereplace.exe heros_hf_nobk_template.sql __tmp.sql AAAAA 30001
simplereplace.exe __tmp.sql heros_hf_nobk.sql BBBBB 30006
del __tmp.sql



你可能感兴趣的:(编程语言-CPP,系统运维-WINDOWS)