Thursday, 30 May 2019
c - feof(in) != EOF doesn't make while loop stop when at the end of file?
Answer
Answer
int main ()
{
FILE *in;
in = fopen("input.txt","r");
char c = fgetc(in);
while(feof(in) != EOF)
{
printf("%c",c);
c = fgetc(in);
}
}
feof(in) != EOF
doesn't stop the while loop from stopping but something like !feof(in)
seems to work. Any ideas?
Answer
feof
doesn't return EOF
on end of file; it returns true
, which is not equal to EOF
.
fgetc
will return EOF
when it hits end-of-file. Your code should be written as
int main ()
{
FILE *in;
in = fopen("input.txt","r");
int c = fgetc(in); // note int not char
while(c != EOF) // compare c to EOF
{
printf("%c",c);
c = fgetc(in);
}
}
You should not use feof
as a loop condition, as it won't return true
until after you attempt to read past the end of the file, meaning your loop will execute once too often.
Subscribe to:
Post Comments (Atom)
php - file_get_contents shows unexpected output while reading a file
I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print ...
-
I have an app which needs a login and a registration with SQLite. I have the database and a user can login and register. But i would like th...
-
I got an error in my Java program. I think this happens because of the constructor is not intialized properly. My Base class Program public ...
-
I would like to use enhanced REP MOVSB (ERMSB) to get a high bandwidth for a custom memcpy . ERMSB was introduced with the Ivy Bridge micro...
No comments:
Post a Comment