#include <iostream>
#include<fstream>
using namespace std;
void myreplace(const string& filename,const string& tofind,const string& toreplace);
int main()
{
myreplace("/Users/xuconglong/Desktop/text/1.txt", "5", "m");
return 0;
}
void myreplace(const string& filename,const string& tofind,const string& toreplace)
{
ifstream fin(filename.c_str(),ios_base::binary);
string str(1024*1024*2,0);
fin.read(&str[0],2*1024*1024);
fin.close();
ofstream fout(filename.c_str(),ios_base::binary);
string::size_type beg=0;
string::size_type pos;
string::size_type find_size=tofind.size();
string::size_type replace_size=toreplace.size();
if(0 == find_size)
{
cout << "no such file or no content" << endl;
return;
}
unsigned count = 0;
while((pos=str.find(tofind,beg))!=string::npos)
{
fout.write(&str[beg],pos-beg);
fout.write(&toreplace[0],replace_size);
beg=pos+find_size;
count++;
}
fout.write(&str[beg],strlen(str.c_str())-beg);
fout.close();
cout << "has replaced number:" << count << endl;
}
【c++文本文件操作之替换】mac系统xcode编译环境
最新推荐文章于 2024-08-09 17:35:31 发布