Monday, December 7, 2009

Error handling

The standard I/O functions maintain two indicators with each open stream to show the end-of-file and error status of the stream. These can be interrogated and set by the following functions:

#include

void clearerr(FILE *stream);

int feof(FILE *stream);

int ferror(FILE *stream);

void perror(const char *s);

Clearerr clears the error and EOF indicators for the stream.

Feof returns non-zero if the stream's EOF indicator is set, zero otherwise.

Ferror returns non-zero if the stream's error indicator is set, zero otherwise.

Perror prints a single-line error message on the program's standard output, prefixed by the string pointed to by s, with a colon and a space appended. The error message is determined by the value of errno and is intended to give some explanation of the condition causing the error. For example, this program produces the error message shown:

#include
#include

main(){

fclose(stdout);
if(fgetc(stdout) >= 0){
fprintf(stderr, "What - no error!\n");
exit(EXIT_FAILURE);
}
perror("fgetc");
exit(EXIT_SUCCESS);
}

/* Result */
fgetc: Bad file number

Example 9.8

Well, we didn't say that the message had to be very meaningful!

0 comments:

Post a Comment