Saturday, 31 August 2013

Error handling | C Programming Language Tutorial



Error handling

It is possible that an en-or may occur during I/O operations on a file. Typical en-or situations include:
1. Trying to read beyond the end of file mark.
2. Device overflow
3. Trying to use a file that has not been opened.
4. Opening a file with an invalid file name.
5. Attempting to write to a write protected file.
6. Trying to perform an operation on a file when the file is opened for another type of operation. he standard I/O functions maintain two indicators with each open stream to show the end-of file and en-or status of the stream.

These can be interrogated and set by the following functions: 
#include <stdio.h>
void clearerr(FILE *stream);
int feof(FILE *stream);
int ferror(FILE *stream);
void perror(const char *s);
clearer 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 ermo and is intended to give some explanation of the condition causing the error.

For example, this program produces the error message shown:
#include <stdio.h>
#include <stdlib.h>
main()
{
fclose(stdout);
if(fgetc(stdout) >= 0)
{
fprintf(stderr, "What - no error!\n");
exit(EXIT _FAILURE);
}
ferror("fgetc");
exit(EXIT _SUCCESS);
}

/* Result */
fgetc: Bad file number

0 comments:

Post a Comment

 

C Programming Language Interview Questions and Answers Tutorial for beginners. Copyright 2013 All Rights Reserved