Hacker News new | ask | show | jobs
by andreyv 1569 days ago
In C, and many other languages, the file stream error state is saved after each operation, so you can skip error checking on every output line and only do

  if (fflush(stdout) != 0 || ferror(stdout) != 0)
  {
    perror("stdout");
    return EXIT_FAILURE;
  }
at the end of the program. The same should be done for stderr as well.

In GNU programs you can use atexit(close_stdout) to do this automatically.

2 comments

I wish this post were higher up, since it shows the idiomatic way to deal with that problem, unlike the article. Obviously the designers of the Unix i/o interface thought about this and provided for a simple way of handling it.
Would perror() return the first/oldest error or the last?
Right — ferror() does not set errno, and so perror() is not appropriate here. fprintf(stderr, ...) would be better.