Error Handling

Based upon return values.


Requires the preprocessor directive:


#include <errno.h>


errno defined within errno.h header file in the C standard library, used by library functions to store a value upon error detection.


perror() function displays a passed string followed by the textual representation of the errno.


strerror() function returns a pointer to the text representation of the errno.


This piece of code tries to open a non-existent file and prints error messages to the screen:

#include <stdio.h>
#include <stddef.h> //may be required in some IDEs (e.g. Eclipse)
#include <errno.h>
#include <string.h>

int main(){

	FILE *filePointer;


	if (filePointer == NULL) {

		printf("Error number: %dn", errno) ;
		perror("Text representation from perror: ") ;
		printf("Error opening file: %sn", strerror( errno ));

	fprintf(filePointer,"Here's some data being written to a text filen");


	return 0;

Leave a Reply