puts() returns 13 with no pipe and with pipe to /dev/full, which I just learned is due to buffering.
What worked for me initially was the POSIX write() function:
#include <stdlib.h>
#include <unistd.h>
int main(void)
{
int status;
status = write(1, "Hello World!\n", 13);
if (status < 0) { return EXIT_FAILURE; }
return EXIT_SUCCESS;
}
-----
As someone else commented, fflush() gives the desired error response.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int status;
puts("Hello World!");
status = fflush(stdout);
if (status < 0) { return EXIT_FAILURE; }
return EXIT_SUCCESS;
}
-----
andreyv probably has the best alternative[1], which is checking fflush() and ferror() at the program's end and calling perror(). It's better because it outputs an actual error message on the current terminal, and you don't need to write a special error checking wrapper.
puts(), like printf() and all the C-standardised "stdio" functions use buffered writes. So that is also buggy, because the buffer won't be flushed until after main() returns. You need to call and check the return value of "fflush(stdout)" manually to get the correct result.