【发布时间】:2010-08-09 15:04:08
【问题描述】:
问题是在 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/src/dest/g" input.txt。直接在 C 中执行此操作没有多大意义(至少在我看来)。 -
@Jerry Coffin... 先生,但这个问题是为了测试我们对在 C 中处理文件的理解!!!
-
“这个问题是为了测试我们对在 C 中使用文件的理解” - 这是一个家庭作业问题吗?如果是这样,您可能需要添加“作业”标签。
-
@Merlyn....我没有添加,但上次登录时添加了其他人...。看来其他人又删除了它!!!!