轉:關於使用fputc輸出,文件結尾多一個字符的問題

下面程序將file1.c中數據複製到file2.c中

但是在file2.c結尾處卻多了一個字符

 

#include <stdio.h>

int main()

{

FILE *in,*out;

char ch,infile[10],outfile[10];

printf("Enter the infile name:/n");

scanf("%s",infile);

printf("Enter the outfile name:/n");

scanf("%s",outfile);

in=fopen(infile,"r");

out=fopen(outfile,"w");

while(!feof(in))

{

ch=fgetc(in);

fputc(ch,out);

putchar(ch);

}

fclose(in);

fclose(out);

 

}

 

原因在於你多循環了一次
因爲在你ch = fgetc( fp1 );
這個時候的ch爲3 你把他放入fp2 沒錯
但這時的位置還沒seek到文件的末尾
所以你又進行了一次while
這時ch = fgetc( fp1 );讀出了EOF
也就是文件的結尾
你把EOF也給了fp2
所以就多了個你所謂的那個兩點y(應該和編碼有關係吧)

修改後就好了

#include <stdio.h>

int main()

{

FILE *in,*out;

char ch,infile[10],outfile[10];

printf("Enter the infile name:/n");

scanf("%s",infile);

printf("Enter the outfile name:/n");

scanf("%s",outfile);

in=fopen(infile,"r");

out=fopen(outfile,"w");

ch=fgetc(in);

while(!feof(in))

{

fputc(ch,out);

putchar(ch);

ch=fgetc(in);

}

fclose(in);

fclose(out);

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章