Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Many implementations of the stdio package adjust their behavior slightly if stdout is a terminal. To make the determination, these implementations perform some operation that fails (with ENOTTY) if stdout is not a terminal. Although the output operation goes on to complete successfully, errno still contains ENOTTY. This behavior can be mildly confusing, but it is not strictly incorrect because it is only meaningful for a program to inspect the contents of errno after an error has been reported. More precisely, errno is only meaningful after a library function that sets errno on error has returned an error code.

Code Block
bgColor#FFcccc
langc
errno = 0;
printf("This\n");
printf("is\n");
printf("a\n");
printf("test.\n");
if (errno != 0) {
  fprintf(stderr, "printf failed: %s\n", strerror(errno));
}

...

This compliant solution uses ferror() to detect an error. In addition, if an early call to printf() fails, later calls may modify errno, whether they fail or not, so the program cannot rely on being able to detect the root cause of the original failure if it waits until after a sequence of library calls to check.

Code Block
bgColor#ccccff
langc
printf("This\n");
printf("is\n");
printf("a\n");
printf("test.\n");
if (ferror(stdout)) {
  fprintf(stderr, "printf failed\n");
}

...