How does the fscanf function work?

You have to focus in the double loop you have there:

while(fscanf(in,"%s",name) != EOF){
  fscanf(in,"%s",surname);
  while( !feof(in) && fscanf(in,"%d",&grade)>0 ){
    n_grades++;
  }
}

EOF stands for End Of File, so the first loop will continue until the end of the file is found, i.e. until the file pointer reaches the end of the file.

Now remember that your file has data like this: Steve Stevenson 2 9 4 3 2.

So the first while will try to read a name, if EOF is not reached yet, that means that you read a name and you assigned it in name. Here you read Steve.

Now this fscanf(in,"%s",surname); will read the second string from the current row in the file in points to (notice the %s, which indicates that we expect to read a string). You read Stevenson and you assign it to surname.

Then, in the second while, you read until you do not reach EOF AND until you read integers. If you check the ref of fscanf() you will see:

Return Value On success, the function returns the number of items of the argument list successfully filled. This count can match the expected number of items or be less (even zero) due to a matching failure, a reading error, or the reach of the end-of-file.

If a reading error happens or the end-of-file is reached while reading, the proper indicator is set (feof or ferror). And, if either happens before any data could be successfully read, EOF is returned.

So when you read a newline for example, you will have read zero integers, thus you will exit the loop.

That way you will eventually parse all the file.

On the spirit of the example I have here with scanf(), you could re-write the code as such:

while(fscanf(in,"%19s",name) != EOF) {

in order to avoid overflowing. Here 20 is the size of your array.

Leave a Comment