检测用C,如果输出到终端 [英] Detect in C if outputting to a terminal

查看:90
本文介绍了检测用C,如果输出到终端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了OS X和Linux C程序,我要调整基于其是否是怎么回事到终端的输出。我知道,我们已经介绍了如何做到这一点在shell脚本,例如这里:

I'm writing a C program for OS X and Linux, and I want to tweak the output based on whether or not it's going to a terminal. I know we've covered how to do this in a shell script, e.g. here:

<一个href=\"http://stackoverflow.com/questions/911816/detecting-the-output-stream-type-of-a-shell-script\">http://stackoverflow.com/questions/911816/detecting-the-output-stream-type-of-a-shell-script

但我怎么做它在C程序?

But how do I do it in a C program?

推荐答案

使用 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.

由于标准输出总是文件描述符1,你可以这样做:

Since stdout is always file descriptor 1, you can do:

if(isatty(1))
    // stdout is a terminal

这篇关于检测用C,如果输出到终端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆