c 语言字符输出到文件

来源:百度知道 编辑:UC知道 时间:2024/05/23 20:43:20
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
FILE *fp1,*fp2,*fp3;
fp1=fopen("1.txt","r");
fp2=fopen("2.txt","w");
fp3=fopen("3.txt","w");
while(!feof(fp1))
{fputc(fgetc(fp1),fp2);
}
rewind(fp1);
while(!feof(fp1))
{fputc(fgetc(fp1),fp3);
}
if(feof(fp1))
puts("the end of the file");
system("PAUSE");
return 0;
}
1.txt 的内容是 i am a student 但是2.txt 3.txt 的内容输出为什么最后都多了一个字符阿 ?y的上面有两点
怎么避免出现这种情况呢

读到了EOF,-1,按字符存即255,就是y的上面有两点。
设想一下,fgetc(fp1)读1.txt的最后一个字符,满足
while(!feof(fp1)),
所以继续读入-1并写入到2.txt,3.txt.

修改如下:
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
FILE *fp1,*fp2,*fp3;
char c;
fp1=fopen("1.txt","r");
fp2=fopen("2.txt","w");
fp3=fopen("3.txt","w");

while(!feof(fp1))
{c=fgetc(fp1);
if(c!=EOF)fputc(c,fp2);
}
rewind(fp1);
while(!feof(fp1))
{c=fgetc(fp1);
if(c!=EOF) fputc(c,fp3);
}
if(feof(fp1))
puts("the end of the file");
system("PAUSE");
fclose(fp1);
fclose(fp2);
fclose(fp3);
return 0;
}