编写文件替换程序

 
        编写文件替换程序th.exe(命令行包括三个参数),替换文件中符合条件的字符串,替换后文件中无与被替换字符串相同的字符串。
例如:th test.txt “abc” “ab”

说明:将test.txt 中的所有“abc”替换为“ab”,替换后test.txt中将找不到完整的“abc 

      

   打开文件,取出文本中所有的字符串到buff中,有一个数组pos记住所有要替换字符串在文本中的开始位置,使用替换算法str_replace替换所有要替换的字符串。

 

 

   源程序如下:

  

   // th.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define TSIZE 10
int pos[TSIZE];//记忆替换字符串的位置
void strpos(char *find,char *str);//找到要替换字符串的在文本中所有的开始位置
char *str_replace(char *find,char *rep,char *string);//用rep替换字符串string中的find
void replace(char *fname,char *orign,char *now);//替文本中的字符串


int main(int argc, char* argv[])
{
 char *fname = argv[1];

 char *orign = argv[2];
 char *now = argv[3];
 replace(fname,orign,now);

 return 0;
}


void strpos(char *find,char *str)
{//找到要替换字符串的在文本中所有的开始位置
 int i,j,k,t = 1;
 for (i = 0 ;i <= TSIZE ;i++)
  pos[i]=0;
 pos[0]=-1;
 for(i = 0;str[i];i++)
 {
  for(j = 0,k = i;str[k] == find[j];j++,k++)
  {
   if(find[j+1] == '/0')
   {
    if(i != pos[t-1])
    {
     pos[t]=i;
     t++;
    }
    
   }
  }
 }
}

char *str_replace(char *find,char *rep,char *string)
{//用rep替换字符串string中的find
 int len1,len2,len3;   //LEN1是要代换的字符串长度 //LEN2是代换后的长度
 char *newstr;       //保存新的串
 int i = 0,j = 0,k = 1, count = 0,t = 0;//count记录 好替换的字符串的个数
 char *p1;
 char *p2;
    strpos(find,string);
 for(int m =1 ;m<=TSIZE;m++)
 {
//  printf("%d/n",pos[m]);
  if(pos[m]>0)
   count++;
 }
 len1 = strlen(rep);
 len3 = strlen(find);

 len2 = strlen(string)+count*(strlen(rep)-strlen(find));
 newstr = (char *)malloc(len2+10);
 p1 = string;
 p2 = newstr;

 while(*(p1+i))
 {
  if(i == pos[k])
  {
   while(*(p2+j) = *(rep+t))
   {
    j++;
    t++;
   }
   t = 0;
   i = i+len3;
 
//   printf("%d次后%s  j值%d/n",k,p2,j);
//   printf("%d次后%s  i值%d/n",k,p1,i);

   k++;

  }
  *(p2+j) = *(p1+i);
  i++;
  j++;
 }
 *(p2+j) = '/0';
// printf("%d   /n",k);
 return newstr;

}

void replace(char *fname,char *orign,char *now)
{//替文本中的字符串
 FILE *fp;
 char *p;
 char buff[500];


 if((fp = fopen(fname,"r")) == NULL){
  printf("不能打开文件./n");
  return;
 }
 while(!feof(fp))
 {
  fgets(buff,500,fp);
 }

 p = (str_replace(orign,now,buff));

 fclose(fp);

 if((fp = fopen(fname,"w")) == NULL){
  printf("不能打开文件./n");
  return;
 }

 fputs(p,fp);
 fclose(fp);
}

 

 

 

以上是上次写的一个,我个人觉得有很多的不成熟,请各位指正!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值