Displaying an error message with the perror() function

To find a failing routine, check the return code of all function calls. After you have found the failing routine, use the perror() function after the routine to display the error message. perror() displays the string that you pass to it and an error message corresponding to the value of errno. perror() writes to the standard error stream (stderr). Figure 1 is an example of a routine using perror().

By default, the errno2 value will be appended to the end of the perror() string. If you do not want the errno2 value appended to the perror() string, set the _EDC_ADD_ERRNO2 environment variable to 0.

Figure 1. Example of a routine using perror()
   #include <stdio.h>
   int main(void){
      FILE *fp;

      fp = fopen("myfile.dat", "w");
      if (fp == NULL)
         perror("fopen error");
   }