我只是想读取文件的每个字符并将其打印出来,但是当文件完成阅读时,但我得到了一堆?完成阅读后.我如何解决它?
#include <stdio.h>
int main(void){
FILE *fr; /* declare the file pointer */
fr = fopen ("some.txt", "r"); /* open the file for reading */
/* elapsed.dta is the name of the file */
/* "rt" means open the file for reading text */
char c;
while((c = getc(fr)) != NULL)
{
printf("%c", c);
}
fclose(fr); /* close the file prior to exiting the routine */
/*of main*/
return 0;
}
Run Code Online (Sandbox Code Playgroud)
尽管它的名称,getc返回一个int,而不是一个char,以便它可以表示所有可能的char值,此外,EOF(文件结束).如果getc返回a char,则无法在不使用文件中可能存在的值之一的情况下指示文件结尾.
因此,要修复代码,必须先将声明更改char c;为int c;以便在返回时保留EOF标记.然后,您还必须更改while循环条件以检查EOF而不是NULL.
您也可以feof(fr)单独调用文件结尾来读取字符.如果你这样做,你可以离开c的char,但你必须打电话给feof()你读的字符之后,但在打印出来之前,并使用break走出循环.