//todo 将指定文本文件中所有单词均替换为另一个单词 P306
#include <stdio.h>
#include <string.h>
int str_replace(char oldstr[],char newstr[],char str[]);
int main(int argc,int *argv[]){ // 命令行参数
char buff[256];
FILE *fp1,*fp2;
if(argc<5){
printf("用法:repword olfile newfile oldword newword\n");
return -1;
}
if((fp1 = fopen(argv[1],"r"))==NULL){
printf("不能打开%s文件\n",argv[1]);
}
if((fp2 = fopen(argv[2],"w")) == NULL){
printf("不能建立%s文件\n",argv[2]);
return -1;
}
while(fgets(buff,256,fp1) != NULL){
while(str_replace(argv[3],argv[4],buff) != -1);
fputs(buff,fp2);
}
fclose(fp1);
fclose(fp2);
return 0;
}
int str_replace(char oldstr[],char newstr[],char str[]){
int i,j,k,location=-1;
char temp[256],temp1[256];
for(i=0;str[i] && location== -1;i++){
for(j=i,k=0;str[j]==oldstr[k];j++,k++){
if(!oldstr[k+1]) location = i; // ???
}
}
if(location != -1){
for(i=0;i<location;i++) temp[i] = str[i];
temp[i] = '\0';
strcat(temp,newstr);//????
for(k=0;oldstr[k];k++);
for(i=0,j=location;str[j];i++,j++){
temp1[i] = str[j];
}
temp1[i] = '\0';
strcat(temp,temp1);
strcpy(str,temp);
return(location);
}else return (-1);
}