What happen when the stream is in an error state?

This is a discussion on What happen when the stream is in an error state? within the C Programming forums, part of the General Programming Boards category; In C++, when the stream is in an error state (e.g. eofbit being set), we cannot perform either read or ...

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

    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:

    Code:
    #include <stdio.h>
    
    int main( void )
    {
        int ch;
    
        while ( getchar() != EOF ) ;
        if ( feof(stdin) )
        {
            printf("Oops...EOF!\n");
        }
        /* Surprisingly! Can still read from stdin */
        putchar( getchar() );
        if ( !feof(stdin) )
        {
            printf("Why EOF is unset?");
        }
    
        return 0;
    }
    runing this program, I got
    Code:
    745a2344faz
    ^Z
    Oops...EOF!
    1212
    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 08:58 AM.

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    >Why?
    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, 04: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, 09:40 AM
  5. Replies: 9
    Last Post: 07-01-2002, 08:50 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21