C++ 将一个文件里面的相同的一个字符串替换成另一个字符串

C++ 将一个文件里面的相同的一个字符串替换成另一个字符串

// change_str_in_file.cpp : Defines the entry point for the console application.
//
/*
  How to change one string in a file ?
  use this application.
  Created 2014-4-11 by DMD 
*/
/*********************************************
Example:
change_str.bat

@echo on
replace1to2 "a.txt" "HELLO" "123"
pause
@echo off
********************************************/

#include "stdafx.h"

#include <iostream>
using namespace std;

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>

#include <wx\wx.h>
#include <string>

// wxWidget Library
#include <wx/ffile.h>
#include <wx/file.h>
#include <wx/filename.h>

#include <fstream>

bool replace_string(const wxString& filename,
					const wxString& strOld,
 			        const wxString& strNew);


int main(int argc,char *argv[])//设定参数 
{
	cout<<"Hello! start change string:"<<endl;
	printf("input 1: %s\n",argv[1]);
	printf("input 2: %s\n",argv[2]);
	replace_string(argv[1],argv[2],argv[3]);
	Sleep(100);
	return 0;
}

/****************************************************
  replace strOld to strNew in a file
*****************************************************/
bool replace_string(const wxString& filename,
 					const wxString& strOld,    
					const wxString& strNew)
{
	wxFFile filehandler;
	wxString FileName   = filename;
	wxString Content    = "";
	if(wxFileExists(FileName))
	{
		 printf("Successfully!, Open file: %s .\n",filename.c_str() );
		 filehandler.Open(FileName);
		 filehandler.ReadAll(&Content);
		 filehandler.Close();
	}
	else
	{
		printf("File: %s is not exist ! \n",filename.c_str());
		return false;
	}

	int ifind =Content.find(strOld);
	if(ifind>=0)
	{
		int iCount = Content.Replace(strOld,strNew);
		if(iCount > 0)
		{
			wxFile file1(FileName, wxFile::write);
			if (!file1.IsOpened()) 
			{
				file1.Close();
				return false;
			}
			file1.Write(Content);
			file1.Close();
		}
	}
	return true;
}


完!

测试成功!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值