4 ms·
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
by andreyv 5y 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.
- Asooka 5y agoI 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.
- PennRobotics 5y agoWould perror() return the first/oldest error or the last?
- andreyv 5y agoRight — ferror() does not set errno, and so perror() is not appropriate here. fprintf(stderr, ...) would be better.