There are multiple typos on this line:
while (fscan(file("%s %s %d", name, degree, &mark) != EOF);
printf("%s %s %d", name, degree, mark);
It should read:
while (fscanf(file, "%s %s %d", name, degree, &mark) == 3)
printf("%s %s %d", name, degree, mark);
Can you spot the 4 mistakes?
- The function is called
fscanf
file
is an argument followed by ,
, not a function name followed by (
- you should keep looping for as long as
fscanf
converts 3 values. If conversion fails, for example because the third field is not a number, it will return a short count, not necessarily EOF
.
- you typed an extra
;
after the condition. This is parsed as an empty statement: the loop keeps reading until end of file, doing nothing, and finally executes printf
just once, with potentially invalid arguments.
The programmer uses char
arrays and passes their address to fscanf
. If he had used pointers (char *
), he would have needed to allocate memory to make them point to something and pass their values to fscanf
, a different approach that is not needed for fixed array sizes.
Note that the code should prevent potential buffer overflows by specifying the maximum number of characters to store into the arrays:
while (fscanf(file, "%9s %4s %d", name, degree, &mark) == 3) {
printf("%s %s %d", name, degree, mark);
}
Note also that these hard-coded numbers must match the array sizes minus 1, an there is no direct way to pass the array sizes to fscanf()
, a common source of bugs when the code is modified. This function has many quirks and shortcomings, use with extreme care.