看似简单的问题,处理起来感觉不是那么轻松。
你的问题没有说太清楚,这里给出一个简单的实例。思路是一行一行的读然后查找再替换,简化读写。设一文件w00.dat,内容为:
I like you, do you like me?
like father like son.
When I was a child I fell in love with a very pretty young lady.
In my heart,she was like a fairy .
I love her till this time of today!
I am young,handsome and full of energy. like and alike are like.
That is all, thank you! likely is alike as likely as not.
编写一个c程序,将上述文件中的所有单词like改为LOVE,显示结果并写入文件w01.txt中。
本题的一个完整的c程序如下,程序在win-tc和Dev-c++下调试通过。
#include
#include
#include
#define N 100 /*设文章不超过100行,可更改*/
char s[N][81];
int main()
{
int i=0,j,max;
char *p;
FILE *fp1,*fp2;
fp1=fopen("w00.txt","r");
fp2=fopen("w01.txt","w");
while (i
p=strchr(s[i],'\n');
if(p)
*p='\0';
i++;
}
max=i; /*max为文章实际的最大行数*/
for(i=0;i
)
{
s[i][j+1]='L';
s[i][j+2]='O';
s[i][j+3]='V';
s[i][j+4]='E';
}
else if (s[i][0]=='l'&&s[i][1]=='i'&&s[i][2]=='k'&&s[i][3]=='e'&&(!isalpha(s[i][4])))/*考虑当like位于一行开头时的情况*/
{
s[i][0]='L';
s[i][1]='O';
s[i][2]='V';
s[i][3]='E';
}
}
for(i=0;i
printf("%s\n",s[i]);
}
fclose(fp1);
fclose(fp2);
getch();
return 0;
}
#include
#include
//By cockhorseman QQ:1004828288
void main()
{
FILE *p;
char a[200],c,b,i;
if((p=fopen("zifu","r"))==0)//打开文件
{
printf("文件打开失败!\n");
}
else
{
fscanf(p,"%s",a);
printf("你要替换的字符\n");
c=getchar();
getchar(); //结束接收第一个字符
printf("你要替换成的字符\n");
b=getchar();
for(i=0;a[i]!=0;i++)//实现替换
{
if(a[i]==c)a[i]=b;
}
printf("%s\n",a);
fprintf(p,"%s",a);//文件输出
fclose(p);
}
}
核心:
freopen("r","XXX.txt",stdin);
读入
查找
替换
freopen("w","XXX.txt",stdout);
输出