Is there a way for a C program to determine whether its output to stdout is being redirected?
(I would like to be able to display to stderr more warning messages if it is redirected than if not).
Is there a way for a C program to determine whether its output to stdout is being redirected?
(I would like to be able to display to stderr more warning messages if it is redirected than if not).
The standard unix-y way is
NAME
isatty - test whether a file descriptor refers to a terminal
SYNOPSIS
#include <unistd.h>
int isatty(int fd);
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
The more unixy way would be to take a flag (say, -v or --verbose) to increase the level or quantity of messages written to stderr. Otherwise a user may be somewhat surprised to find that more is written to a file or pipe than to the terminal. (Part of the Unix philosophy is "principle of least astonishment", which means that consistency is valued.)