C++替换文件中指定的内容

/*实现替换文件中指定的内容
----Created by cryking----
--------2012.02.12--------*/
#include<iostream>
#include<fstream>
#include<string.h>
#include<stdlib.h>
using namespace std;

char *strstr_rep(char *source,char *old,char *ne)//字符替换
{
 char *org=source;
 char temp[256];
 int old_length=strlen(old);//获得将被替换的字符串的大小
 int i,j,k,location=-1;
 for(i=0;source[i]&&(location==-1);++i)//location查找将被替换的字符串的位置
  for(j=i,k=0;source[j]==old[k];j++,k++)
   if(!old[k+1])
    location=i;
   if(location!=-1)//开始替换
   {
    for(j=0;j<location;j++)//先把被替换的字符串的前一部分COPY到temp
     temp[j]=source[j];
    for(i=0;ne[i];i++,j++)//再把替换的新字符串COPY到temp
     temp[j]=ne[i];
    for(k=location+old_length;source[k];k++,j++)//把剩下的内容COPY到temp
     temp[j]=source[k];
    temp[j]=NULL;
    for(i=0;source[i]=temp[i];i++); //把临时字符串temp复制给source
   }
   return org;  
}
int main()
{
 fstream outfile("test.txt",ios::out|ios::in);
 char ch;
 char buffer[255];
 int i=0,k=0;
 if(!outfile){  
  cout<<"不能打开目的文件:test.txt"<<'\n';  
  exit(1);  
 }
 
 outfile.unsetf(ios::skipws); 
 while (outfile>>ch) {//将文件全部内容读出到buffer
  buffer[i]=ch;
     i++;
 } 
 strstr_rep(buffer,"2222","8888");//将"2000"替换为8888"
 outfile.close();
  ofstream infile("test.txt");
  while(k!=i){infile<<buffer[k];k++;}//将buffer全部写入到文件
  outfile.close();
  return 0;
}
很久没敲代码了,唉。。。手生了!!!
  • 3
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值