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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With