如何检测何时重定向输出? [英] How do I detect when output is being redirected?

查看:68
本文介绍了如何检测何时重定向输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用C编写的Win32应用程序,可以通过printf()将其控制台输出重定向到日志文件。

I have a Win32 application written in C that can have its console output via printf() redirected to a log file.

它如果我可以安装我的应用程序,那就太好了。

It would be nice if I could have my app. detect if it had been started with or without a redirect '>'.

有什么想法吗?

推荐答案

汤姆,谢谢您的输入。

我做了一些实验,发现这对我有用。

I did some experiments and found this works for me..

fpost_t pos ;

fgetpos (stdout, & pos) ;

将应用程序的输出重定向到文件时,fgetpos()会将pos设置为零。这是有道理的,因为它为您提供了新近打开的stderr。 编辑:实际上,如果文本已被重定向到日志/文件,则返回的值可能是正整数。因此,在您的代码中,您将遇到类似 if(pos> = 0)bfRedirected = TRUE;

When an application's output is being redirected to a file, fgetpos() sets 'pos' to zero. It makes sense since its freshly opened stderr for you. Actually, the value returned may be a positive integer if text has already been redirected to the log/file. So in your code you'd have something like "if (pos >= 0) bfRedirected = TRUE ;"

当应用程序的输出未重定向时,它会控制台设备-不是文件,因此fgetpos()会将'pos'设置为-1。

When an application's output is not being redirected - it's going to the console device - not a file, so fgetpos() will set 'pos' to -1.

这篇关于如何检测何时重定向输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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