如何确定C中的stdout“指向”?

时间:2011-09-12 06:20:51

标签: c posix stdout

我希望能够判断我的程序的stdout何时被重定向到文件/设备,以及什么时候才能在屏幕上正常打印。如何在C中完成?

更新1 :从评论中看,它似乎与系统有关。如果是这样,那么如何使用符合posix标准的系统呢?

5 个答案:

答案 0 :(得分:5)

也许是isatty(stdout)

修改:正如Roland和tripleee建议的那样,更好的答案是isatty(STDOUT_FILENO)

答案 1 :(得分:3)

我担心你不能,至少在标准C中以平台独立的方式。标准输入/输出背后的想法是C将从标准位置执行IO。该标准位置可以是终端或文件或其他任何内容,这不是C的考虑因素。因此您无法检测当前使用的标准IO。

编辑:如果特定于平台的解决方案适合您,请参考其他答案(并相应地编辑问题)。

答案 2 :(得分:3)

查找isatty,更一般地fileno

答案 3 :(得分:2)

如果特定于Linux的解决方案没问题,您可以检查进程的/proc目录下的符号链接。如,

$ exec 3>/dev/null
$ ls -l /proc/$$/fd
total 0
lrwx------ 1 root root 64 Sep 12 03:28 0 -> /dev/pts/1
lrwx------ 1 root root 64 Sep 12 03:29 1 -> /dev/pts/1
lrwx------ 1 root root 64 Sep 12 03:29 2 -> /dev/pts/1
lrwx------ 1 root root 64 Sep 12 03:29 255 -> /dev/pts/1
l-wx------ 1 root root 64 Sep 12 03:29 3 -> /dev/null

答案 4 :(得分:0)

您可能需要查看此内容:

http://www.cplusplus.com/reference/clibrary/cstdio/freopen/

我引用了这个链接:

freopen

Reopen stream with different file or mode
freopen first tries to close any file already associated with the stream given as third parameter and disassociates it.
Then, whether that stream was successfuly closed or not, freopen opens the file whose name is passed in the first parameter, filename, and associates it with the specified stream just as fopen would do using the mode value specified as the second parameter.
This function is specially useful for redirecting predefined streams like stdin, stdout and stderr to specific files.

虽然我不确定这是否会帮助你找到它首先指出的内容。