Section 15.4 More Efficient File Reading
Normally, we won’t know how many numbers are in a file before we open it, so how do we know when to stop reading from the file? It turns out, the
fscanf()
function actually tells us when we reach the end of the file via a return value of EOF. This is so important that I’ll say it again: It is the the return value of the fscanf()
function through which we’ll know when the end of the file has been reached. It is not the value that was read. This is a super common cause for confusion so be sure to ask lots of questions and make sure you understand the difference. To sum up: Instead of using a for
loop to read from the file, from now on we’ll simply keep reading until we reach the end of the file, indicated by the return value of EOF
of the fscanf()
function.Let’s look at how this is done. This time, the file simply contains the following numbers:
6 3 -55 4 67 299 -4 -7 -3
Pretend you don’t know how many numbers there are in the file.
Notice how the
fscanf()
function communicates with us in two ways: Values read from the file are transmitted to us via the variables (with ampersands in front of them) that appear inside the parentheses (in this case we call the variable num
). On the other hand, the return value (which we store in the variable result
here) signifies whether the end of the file has been reached. When this is the case, the return value equals EOF
.It is actually not even necessary to store the return value of the
fscanf()
function in a separate variable as we see in the even more compact way of writing the code below. But if you are more comfortable in using the extra variable then by all means, please do!Here is a very efficient way to accomplish file reading until the end of the file: