问题是查找并替换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