how to stop reading from file in C
I am just trying to read each character of the file and print it out but when the file finishes reading, but I am getting a bunch of ? after it finishes reading. How do I fix it?
#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;
}
In spite of its name, getc
returns an int
, not a char
, so that it can represent all of the possible char values and, in addition, EOF
(end of file). If getc
returned a char
, there would be no way to indicate the end of file without using one of the values that could possibly be in the file.
So, to fix your code, you must first change the declaration char c;
to int c;
so that it can hold the EOF marker when it is returned. Then, you must also change the while loop condition to check for EOF
instead of NULL
.
You could also call feof(fr)
to test end of file separately from reading the character. If you did that, you could leave c
as a char
, but you would have to call feof()
after you read the character but before you printed it out, and use a break
to get out of the loop.
If unsuccessful, fgetc()
returns EOF.
int c;
while ((c = getc(fr)) != EOF)
{
printf("%c", c);
}
Change this
char c;
while((c = getc(fr)) != NULL)
{
printf("%c", c);
}
to
char c;
int charAsInt;
while((charAsInt = getc(fr)) != EOF)
{
c = (char) charAsInt;
printf("%c", c);
}
In other words: You need to compare against EOF
, not NULL
. You also need to use an int
variable to receive the return value from fgetc
. If you use a char
, the comparison with EOF
may fail, and you'll be back where you started.
fgetc()
returns EOF
on end-of-file, not NULL
.
Replace "NULL" with "EOF".
Others have already addressed the issue you're having, but rather than using printf("%c", c);
it is probably much more efficient to use putchar(c);
. There is quite a bit of overhead involved when you ask printf
to print just one character.
getc returns an int.
change char c, to int c.
also getc returns EOF, change your test against NULL to a test against EOF
精彩评论