开发者

How can I determine what stdout "points" to in C?

I want to be able to tell when my program's stdout is redirected to a file/device, and when it is left to print normally on the screen. How can this be done in C?

Update 1:开发者_如何学Go From the comments, it seems to be system dependent. If so, then how can this be done with posix-compliant systems?


Perhaps isatty(stdout)?

Edit: As Roland and tripleee suggest, a better answer would be isatty(STDOUT_FILENO).


Look up isatty and more generally fileno.


I am afraid that you can't, at least with standard C in a platform independent manner. The idea behind standard input/output is that C will do it's IO from a standard place. That standard place could be a terminal or a file or anything else, that is not the consideration of C. So you can't detect what is standard IO currently used.

EDIT: If a platform specific solution is okay for you then please refer to other answers (and also edit the question accordingly).


If a Linux-specific solution is OK, you can examine the symlinks under the /proc directory for your process. E.g.,

$ 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


You might want to check this out:

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

I'm quoting from the link:

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.

Though I'm not sure if this'll help you find out what it is pointing to in the first place.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜