Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: indicated that strerror_r() solution is POSIX only

...

Note that this code first sets errno to 0 to comply with ERR30-C. Set errno to zero before calling a library function known to set errno, and check errno only after the function returns a value indicating failure.

Compliant Solution (POSIX)

The compliant solution uses the POSIX strerror_r() function, which has the same functionality as strerror() but guarantees thread safety.

Code Block
bgColor#ccccff
errno = 0;
FILE* fd = fopen( filename, "r");
if (fd == NULL) {
  char errmsg[BUFSIZ];
  if (strerror_r( errno, errmsg, BUFSIZ) != 0) {
    /* handle error */
  }
  printf("Could not open file because of %s\n", errmsg);
}

Note that Linux provides two versions of strerror_r(), known as the XSI-compliant version and the GNU-specific version. This Compliant Solution compliant solution assumes the XSI-compliant version. You can get the XSI-compliant version if you compile applications in the way POSIX requires (that is, by defining _POSIX_C_SOURCE or _XOPEN_SOURCE appropriately). Check your strerror_r() manpage man page to see which version is available on your system.

...