I am trying to print contents of a file with approximately 4000 characters. Somehow the program records only the first 220 characters and terminates.
int main(vo
I think the code is fine, apart from the fact that you should change the ch
to int
.
fgetc() returns
int
"EOF
on end of file or error"So, first, you have to change the ch
to int
, as some return values from fgetc()
may not fit into a char
.
Now, in the second case, you're not checking the return value of fgetc()
against EOF
to detect any error . You're simply taking the return value and trying to store those values into the array. Actually, when the end of file is reached, there is nothing more to be read, and all the further reads on the same file pointer will return you error.
It is most likely that those values. after 220
in your case are valid , at all.
So, to the statement in your question,
(EOF occurs unexpectedly)
is wrong. It occurs just fine, you're ignoring it and running into, well, trouble.
Note:
fgetc()
calls, essentially discarding the result of the first one, and using the second one without any check.gets()
. It suffers from buffer overflow issues. Always use fgets() instead.