問題是查找並替換C文件中的字符串。在C文件中查找並替換
我是C文件新手。我曾嘗試下面的代碼,但我沒有得到任何輸出:
#include<stdio.h>
#include<string.h>
int main()
{
FILE *f1,*f2;
char *src,*dest,*s1,ch,ch1,ch2,ch3;
int i;
f1=fopen("input.txt","rw");
f2=fopen("dummy.txt","rw");
src="mor";
dest="even";
while(ch!=EOF)
{
ch=fgetc(f1);
if(ch==src[0]) //Finding 1st char of src
{
fgets(s1,strlen(src),f1);
if(strcmp(src+1,s1)==0) //Finding occurance of "src" in file
{
fseek(f1,strlen(src)-1,SEEK_CUR);
while(ch1!=EOF) //Copying remaining data into another file
{
ch1=fgetc(f1);
fputc(ch1,f2);
}
fseek(f1,-strlen(src),SEEK_CUR);
for(i=0;i<strlen(dest);i++) //replacing "src" with "dest"
{
ch2=dest[i];
fputc(ch2,f1);
}
fclose(f1);
f1=fopen("input.txt","a");
while(ch3!=EOF) //Appending previosly copied data into 1st file
{
ch3=fgetc(f2);
fputc(ch3,f1);
}
}
}
}
fclose(f1);
fclose(f2);
}
input.txt中的內容是「早晨」。
請指出邏輯中的錯誤,並給出相同的有效代碼。
在此先感謝。
最明顯有效的代碼會是這樣的:'sed的 「S /源/目標/ G」 input.txt'。直接用C做這件事並沒有什麼意義(至少在我看來)。 – 2010-08-09 15:14:28
@Jerry Coffin ...先生,但問題是要測試我們對使用C文件的理解! – 2010-08-09 15:21:52
「這個問題被要求測試我們對使用C文件的理解」 - 這是一個家庭作業問題嗎?如果是這樣,您可能需要添加「作業」標籤。 – 2010-08-10 05:38:04