Problem with fgets reading last line over and over

Discussion in 'C++' started by Trond Valen, Dec 6, 2005.

  1. Trond Valen

    Trond Valen Guest


    Anyone who knows what the reason might be? fgets is supposed to return
    null when reading EOF. I have a test for this, so my while loop should
    exit, but it doesn't ...

    Trond Valen, Dec 6, 2005
    1. Advertisements

  2. Rule #1: Post Code
    Karl Heinz Buchegger, Dec 6, 2005
    1. Advertisements

  3. You forgot to post any code illustrating the observed behavior, so it
    is very difficult to know what the reason might be.

    The following should work:

    #include <stdio.h>

    int main()
    char buf[42];
    char* ptr;

    while ((ptr = fgets(buf, sizeof buf, stdin)) != NULL) {
    /* do something with buf here */
    return 0;

    /Niklas Norrthon
    Niklas Norrthon, Dec 6, 2005
  4. Trond Valen

    mlimber Guest

    Rule #2: Prefer iostreams to C-style file streams:

    Cheers! --M
    mlimber, Dec 6, 2005
  5. Trond Valen

    deane_gavin Guest

    Rule #3: Make sure you test eof correctly with your C++ streams

    Gavin Deane
    deane_gavin, Dec 6, 2005
  6. Rule #4: If you for some reason use C style I/O, make sure you test
    eof correctly with your FILE objects.

    /Niklas Norrthon
    Niklas Norrthon, Dec 7, 2005
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.