How to stop reading from a file in C

I'm just trying to read every character of the file and print it, but when the file finishes reading, but I get a bunch? after reading is completed. How to 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; } 
+6
c stdio
source share
7 answers

Despite its name, getc returns int , not char , so that it can represent all possible char values ​​and, in addition, EOF (end of file). If getc returned char , there would be no way to indicate the end of the file without using one of values ​​that could be in the file.

So, in order to fix your code, you must first modify the char c; declaration char c; to int c; so that he can hold the EOF token when it is returned. Then you must also change the condition of the while loop to check EOF instead of NULL .

You can also call feof(fr) to check the end of the file separately from reading the character. If you have done this, you can leave c as a char , but you will have to call feof() after you read this character, but before you print it, and use break to exit the loop.

+7
source share

If unsuccessful, fgetc() returns EOF.

 int c; while ((c = getc(fr)) != EOF) { printf("%c", c); } 
+2
source share

fgetc() returns EOF at the end of the file, not NULL .

+1
source share

Replace "NULL" with "EOF".

+1
source share

Change it

 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 with EOF , not NULL . You also need to use the int variable to get the return value from fgetc . If you use char , comparison with EOF may fail and you will return to where you started.

+1
source share

Others have already addressed the question you have, but instead of using printf("%c", c); it is probably much more efficient to use putchar(c); . There is quite a bit of overhead when you ask printf print only one character.

+1
source share

getc returns int .

change char c to int c .

also getc returns EOF , change your test to NULL to test with EOF

+1
source share

All Articles