I'm having trouble with file scans and are these 2 expressions equivalent to each other in the manner that they operate?
#include <stdio.h>
FILE *point;
int number
while ( fscanf(point, "%d", &number) != -1)
while ( !feof(point) )
(test file):
39203 Thao Nguyen
92039 Steven Gonzales
For some reason the first statement works for me but the second statement just gives me seg faults, because it keeps reading the file when there not left to be read.
I tried a third way
while ( point != EOF) // but this gives me a error 开发者_如何学JAVAof integer to pointer error
EOF is a constant defined in stdio.h usually as -1. That's the reason that the first one happens to work for you. However, it's bad practice to use the literal -1 as an implementation can theoretically define EOF however it wants. So you really want to do something along the lines of while ( fscanf(point, "%d", &number) != EOF )
See the fscanf man page:
http://www.kernel.org/doc/man-pages/online/pages/man3/scanf.3.html
No, these two are not the same:
while ( fscanf(point, "%d", &number) != -1)
while ( !feof(point) )
fscanf
can return EOF
(which you should be using rather than -1) for multiple reasons:
If the input ends before the first matching failure or conversion, EOF shall be returned. If any error occurs, EOF shall be returned, and errno shall be set to indicate the error.
But feof
:
The feof() function shall return non-zero if and only if the end-of-file indicator is set for stream.
the first statement:
while ( fscanf(point, "%d", &number) != -1)
will ultimately consume the contents of your file (when fscanf returns -1 in most cases, which is EOF) while:
while ( !feof(point) )
will just give you and endless loop since feof just checks if it is the end of file. you need to have something to make your file position pointer move forward.
while ( point != EOF)
will give you and error since point is a pointer to a FILE structure while EOF is an int (as far as EOF is defined most of the time)
精彩评论