如果输出到terminal,则在C中检测

我正在为OS X和Linux编写一个C程序,我想根据它是否要去terminal来调整输出。 我知道我们已经介绍了如何在shell脚本中执行此操作,例如:

检测shell脚本的输出streamtypes

但是我如何在C程序中做到这一点?

使用isatty()

 $ man isatty ISATTY(3) Linux Programmer's Manual ISATTY(3) NAME isatty - does this descriptor refer to a terminal SYNOPSIS #include <unistd.h> int isatty(int desc); DESCRIPTION returns 1 if desc is an open file descriptor connected to a terminal and 0 otherwise. 

由于stdout总是文件描述符1,所以你可以这样做:

 if(isatty(1)) // stdout is a terminal 
 if (isatty (1)) fprintf (stdout, "Outputting to a terminal."); else fprintf (stdout, "Not outputting to a terminal.");