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

Pau*_*rth 21 c linux macos

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

检测shell脚本的输出流类型

但是我如何在C程序中执行此操作?

Lau*_*ves 41

用途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.
Run Code Online (Sandbox Code Playgroud)

由于stdout始终是文件描述符1,您可以这样做:

if(isatty(1))
    // stdout is a terminal
Run Code Online (Sandbox Code Playgroud)


dre*_*lax 5

if (isatty (1))
    fprintf (stdout, "Outputting to a terminal.");
else
    fprintf (stdout, "Not outputting to a terminal.");
Run Code Online (Sandbox Code Playgroud)