Thread: What happen when the stream is in an error state?

  1. #1
    C/C++Newbie Antigloss's Avatar
    Join Date
    May 2005

    What happen when the stream is in an error state?

    In C++, when the stream is in an error state (e.g. eofbit being set), we cannot perform either read or write operation on that stream. But if it's in C, what happen when the stream is in an error state? It seems that we can still read or write on that stream. Consider the following code:

    #include <stdio.h>
    int main( void )
        int ch;
        while ( getchar() != EOF ) ;
        if ( feof(stdin) )
        /* Surprisingly! Can still read from stdin */
        putchar( getchar() );
        if ( !feof(stdin) )
            printf("Why EOF is unset?");
        return 0;
    runing this program, I got
    1Why EOF is unset?
    From the output, we know that stdin is in an error state before the second getchar. But as we can see, getchar was still called successfully. Why? And after that getchar was called, the EOF state for stdin was also unset, why?

    ps, I complied this code with Dev-C++
    Last edited by Antigloss; 10-27-2006 at 07:58 AM.

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Because the C standard imposes no requirements on how an implementation should react to an "error" state such as those returned by feof or ferror. Ignoring it in favor of letting the calling code deal with it is a reasonable, if confusing, interpretation. I chose to go with the disallowing of future operations (like C++) until the indicators are cleared. I think that makes more sense and promotes more robust code, but my personal implementation isn't widely used.
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Stream Server
    By ch4 in forum Networking/Device Communication
    Replies: 18
    Last Post: 06-29-2009, 03:09 PM
  2. Discard wrong data from stream
    By mesmer in forum C Programming
    Replies: 7
    Last Post: 11-16-2008, 02:30 AM
  3. Closing a stream
    By cunnus88 in forum C++ Programming
    Replies: 8
    Last Post: 02-21-2008, 05:15 PM
  4. Help! About text stream and binary stream
    By Antigloss in forum C Programming
    Replies: 1
    Last Post: 09-01-2005, 08:40 AM
  5. Replies: 9
    Last Post: 07-01-2002, 07:50 AM