ILE C/C++ Programmer's Guide

Checking the Errno Value

The <errno.h> header file contains declarations for defined error conditions. Many C functions set errno to specific values, depending on the type of error. These values are also defined in the <errno.h> header file. The implementation of errno contains a function call.

The following errno macros indicate an OS/400 system exception:

For a list of errno macro values, see ILE C/C++ Run-Time Library Functions.

Initializing Errno

Your program should always initialize errno to 0 (zero) before calling a function because errno is not reset by any library functions. Check for the value of errno immediately after calling the function that you want to check. You should also initialize errno to zero after an error has occurred.

Viewing and Printing the Errno Value

Your program can use the strerror() and perror() functions to print the value of errno. The strerror() function returns a pointer to an error message string that is associated with errno. The perror() function prints a message to stderr. The perror() and strerror() functions should be used immediately after a function is called because subsequent calls might alter the errno value.

Example: Checking the errno Value for the fopen() Function

The following figure shows how to check the errno value for the fopen() function.

Figure 161. ILE C Source to Check the errno Value for fopen()




#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
void main(void)
{
FILE *fp;
errno = 0;
fp = fopen("Nofile", "r");
if ( errno != 0 ) 
{
perror("Error occurred while opening file.\n");
exit(1);
}
}


[ Top of Page | Previous Page | Next Page | Table of Contents ]