0
/* The program takes the book info file from the first example of
chapter 28; also reads each line from the file and outputs it to the
screen. */

#include <stdio.h>
#include <stdlib.h>
FILE * fptr;
main()
{
    char fileLine[100]; // Will hold each line of input
    
    fptr = fopen("C:\\users\\DeanWork\\Documents\\BookInfo.txt","r");
    if (fptr != 0)
    {
        while (!feof(fptr))
        {
            fgets(fileLine, 100, fptr);
            if (!feof(fptr))
            {
                puts(fileLine);
            }
        }
    }
    else
    {
        printf("\nError opening file.\n");
    }
    
    fclose(fptr); // Always close your files
    return(0);
}

This is an example from the book C Programming Absolute Beginner's Guide (3rd Edition)

We already have while(!feof(fptr)) to check the file is not empty. Why do we still nedd if(!feof(fptr) to check it again?

user8314628
  • 1,952
  • 2
  • 22
  • 46
  • 4
    Don't use `feof` for this. The book is giving you bad advice. The problem with these books written for beginners is that most of them are written *by* beginners. Unfortunately, they either don't realize it or else don't care as long as they make the sale. – Tom Karzes Oct 10 '21 at 20:10
  • 4
    `while (fgets(fileLine, 100, fptr)) { puts(fileLine); }` - so much simpler – UnholySheep Oct 10 '21 at 20:11
  • The `feof` may change as a result of the `fgets`. – Raymond Chen Oct 10 '21 at 20:30
  • @Raymond But it doesn't affect the statement `puts(fileLine)` inside, does it? – user8314628 Oct 10 '21 at 20:36
  • It is just a terrible example altogether. Like others are saying: don't waste time looking at amateur code. – Cheatah Oct 10 '21 at 20:38
  • 1
    @user8314628 Yes it does. Read the duplicate post. If you did not have the extra `feof` check it will result in `puts` getting called even when `fgets` fails. Better approach is to check return value of `fgets` directly. – kaylum Oct 10 '21 at 20:38
  • 3
    That's apparently a phenomenally bad book. You're right, `feof` is usually unnecessary — so *two* calls to `feof` is doubly unnecessary! Just check `fgets`'s return value. That's the easy & accurate way. You only need `feof` if you're trying to specifically figure out why a previous input call (like `fgets`) failed due to EOF, or an I/O error. – Steve Summit Oct 10 '21 at 20:38

0 Answers0