最后我做到了,我写了这段代码并且运行正常。 它允许您插入文本,之后它将询问您需要搜索哪个单词,以及需要替换的单词是什么,然后执行其工作并将结果保存到新文件(temp.txt )。我的问题是程序可以替换所有特定的单词,除了在EOF之前的文件末尾 这是我的代码
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
FILE *f1,*f2;
int main()
{
int i,Repetition=0,len,len_start,len_end,word_count=0,test=0; //The length of the Word you need to search
char ch,ch1,search_word[10],replace_word[10]; //Array for the word you need to search for
char *ptr=&(search_word[0]),*ptr1=&(search_word[1]); //Pointer on the first index of the search_word array
f1=fopen("pro.txt","w");
if(!f1){ //Condition if the file does not opened correctly
printf("Error opening file\n");
exit(1);
}else{
printf("enter your strings\n");
}
f2=fopen("temp.txt","w");
if(!f2){
puts("error opening file for writing");
exit(1);
}
do{ //Loop to print the string to the file
ch=getchar();
fprintf(f1,"%c",ch);
}while(ch!=EOF);
puts("\nEnter the word you need to search for : ");
scanf("%s",search_word); //Insert the word you need to search
len=strlen(search_word); //Calculate the length of the searched work
printf("\nyour word length is : %d",len); //Print the length of the word you need to search for
printf("\n");
puts("\nEnter the word you need to replace : ");
scanf("%s",replace_word);
fclose(f1); //Close file
printf("File closed....\n");
// The process of reading and editing the file
f1=fopen("pro.txt","r");
printf("\nFile Opened for reading....\n"); //Open file for read and edit
ch = fgetc(f1);
start:
if(test==1)
ch=ch1; //ch1: the next letter after ch read from file
test=1;
ch1 = fgetc(f1);
fprintf(f2,"%c",ch);
while(ch != EOF){ //Read file from first to EOF
if(*ptr==ch){ //ch:the letter read from file ptr: is the pointer that point to the first letter in the search word
if((ch1>=' ' && ch1<='@')){
if(*(ptr1)=='\0'){ //ptr1 is the pointer that point to the next letter in search word (if ptr1 read the '\0' that mean that you reached to last letter in search word
len_end=ftell(f2);
fseek(f2,len_end-len,SEEK_SET);
len_start=ftell(f2);
fprintf(f2,"%s",replace_word);
word_count++;
ptr=&search_word[0];
ptr1=&search_word[1];
goto start;
/*len_end=ftell(f1)-1;
fseek(f1,len_end-len,SEEK_SET);
len_start=ftell(f1);
fseek(f1,0,SEEK_SET);
while(ftell(f1)!=(len_start)){
ch=getc(f1);
fprintf(f2,"%c",ch);
} if(ftell(f1)==(len_start)){
fputs(replace_word,f2);
}
fseek(f1,len_end+1,SEEK_SET);
//printf("test4\n"); }else{
ptr=&search_word[0];
ptr1=&search_word[1];
word_count++;
goto start;*/
//printf("test5\n");
}
//printf("test3\n");
}
ptr++ ;
ptr1++ ;
//printf("test2\n");
}
goto start;
}
fclose(f1);
fclose(f2);
return 0;
}
答案 0 :(得分:0)
使用ch1 = fgetc(f1);
进行预测会导致ch1
上的范围检查在处理完最后一个字符之前在EOF
失败。尝试在范围检查中包括:
if((ch1>=' ' && ch1<='@') || (ch1 == EOF))