您的位置:首页 > 编程语言 > C语言/C++

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

2014-04-11 11:09 357 查看
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;
}


完!

测试成功!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐