Add Book to My BookshelfPurchase This Book Online

Chapter 4 - The Standard I/O Library

UNIX Systems Programming for SVR4
David A. Curry
 Copyright © 1996 O'Reilly & Associates, Inc.

Stream Status
The Standard I/O Library also provides functions for inquiring about and changing the status of a stream:
    #include <stdio.h>
    int ferror(FILE *stream);
    int feof(FILE *stream);
    void clearerr(FILE *stream);
The ferror function returns non-zero when an error occurred while reading from or writing to stream; otherwise, it returns zero. The feof function returns non-zero when the end-of-file condition was detected while reading from stream; otherwise, it returns zero. The clearerr function resets the error and end-of-file indicators on stream.
One of the most common errors made with the Standard I/O Library is to read from a terminal device (usually stdin) and allow the user to indicate an end-of-file with CTRL-D (programs such as mail do this). If the program attempts to read from the terminal again, the second read immediately fails, because the end-of-file condition was already detected on the stream. The proper way to implement this is to call clearerr on the stream immediately after detecting end-of-file.
This error is especially common when porting older programs to newer systems, because the library used to automatically clear the end-of-file condition on stdin if it referred to a terminal device. This behavior was changed several years ago to make things more consistent. Fortunately, it's easy to detect the problem—if the program goes into an infinite loop of reprinting the prompt after you type CTRL-D, you need to add a call to clearerr.

Previous SectionNext Section
Books24x7.com, Inc © 2000 –  Feedback