Lets say we have this piece of code:
while ((ch = getc(fp)) != EOF) {
...
}
This is how i would assume the loop would work, please tell me if it is correct or not/if any mistakes have been made:
getcreads character from I/O streamfpgetcstores it in the variablechchis tested againstEOFwhich is normally equivalent to-1(depending on how it is defined for you).- When
EOFis returned it indicates that theEnd Of Fileindicator for a specific stream has been set. This means that a previous read operation has attempted to read past the end of the file.
One important question i have:
In this loop as getc gets to the end of the file, does it try to eventually read past the end of the file which causes it to eventually return EOF?
More precisely,
getcattempts to read a character from thefpstream.getcreturns anintvalue, and the assignmentch = getc(fp)stores that value inch, if it is representable in thechtype. If it is not representable, it is converted in a manner that depends on thechtype. To avoid complications with this conversion,chshould beint.Yes, the resulting value of
chis compared withEOF. This makes the type important: IfgetcreturnsEOFandchis, say, a character type that cannot represent the value ofEOF, then the conversion will cause a different value to be stored inch, and then it will not compare equal toEOF.EOFmay be −1 in many C implementations, but it is normal for it to have any negativeintvalue.No, an
EOFreturn indicates that either end-of-file has been reached (and a further read was attempted) or an error occurred. C 2018 7.21.7.5 3 says:It means either a previous operation or the current operation attempted to read past the end of the file or a previous operation or the current operation encountered an error (and these previous conditions have not been cleared, as by calling
rewindorclearerr).If the stream is connected to a file of finite and unchanging size, that loop will eventually attempt to read past the end of file, if nothing in the body of the loop resets the file position, at which point
EOFwill be returned and the loop will exit. However, if the stream is connected to some “infinite” supply of data, such as a pipe, it is possible the loop will never encounter the end of the stream.