Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Trouble with fgets

  1. Feb 17, 2010 #1

    CRGreathouse

    User Avatar
    Science Advisor
    Homework Helper

    I've been having trouble with reading past the end-of-file in C. Can anyone find my stupid mistake?

    This is the minimal code needed to cause the error for me:

    Code (Text):
    FILE *f = fopen(name, "r");
    if (!f)
        return;
    pari_sp ltop = avma;
    char line[1100];
    while(fgets(line, 1100, f) != NULL)
        printf(".");
    fclose(f);
    So name is a C-string pointing to a valid filename. The FILE f opens without trouble, and the fgets loop runs through each line in the file. (The actual processing code, which I deleted, parses those lines without trouble; here I replaced it with a line which shows how many lines it reads.) But the last read through fgets does *not* return NULL but causes an application-ending error. fclose is never run.

    What am I doing wrong?
     
  2. jcsd
  3. Feb 17, 2010 #2

    CRGreathouse

    User Avatar
    Science Advisor
    Homework Helper

    Never mind, I fixed it with a rewrite. The problem must have been caused, by some mechanism I don't understand, by the surrounding (complicated) code.
     
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook