【问题标题】:Why can't this Windows command-line program redirect its standard out to a file?为什么这个 Windows 命令行程序不能将其标准输出重定向到文件?
【发布时间】:2014-04-20 08:14:07
【问题描述】:

参考,看这个小程序的源代码,EndPointController.exe: http://www.daveamenta.com/2011-05/programmatically-or-command-line-change-the-default-sound-playback-device-in-windows-7/

基本上,它是一个 Visual Studio C++ 程序,它使用 printf 函数将信息写入命令外壳窗口。

这是我在 Windows 7 x64 上运行程序的示例(使用上面链接中提供的编译二进制文件):

C:\Users\James\Desktop>EndPointController.exe
Audio Device 0: Speakers (High Definition Audio Device)
Audio Device 1: AMD HDMI Output (AMD High Definition Audio Device)
Audio Device 2: Digital Audio (S/PDIF) (High Definition Audio Device)
Audio Device 3: Digital Audio (S/PDIF) (High Definition Audio Device)

C:\Users\James\Desktop>

这非常有效。现在,我将尝试将输出重定向到文件:

C:\Users\James\Desktop>EndPointController.exe > test.txt

C:\Users\James\Desktop>type test.txt

C:\Users\James\Desktop>

没用; test.txt 为空。是权限问题吗?

C:\Users\James\Desktop>dir > test.txt

C:\Users\James\Desktop>type test.txt
 Volume in drive C has no label.
 Volume Serial Number is 16EC-AE63

 Directory of C:\Users\James\Desktop

04/20/2014  03:11 AM    <DIR>          .
04/20/2014  03:11 AM    <DIR>          ..
05/31/2011  06:16 PM             7,168 EndPointController.exe
04/20/2014  03:12 AM                 0 test.txt
               2 File(s)          7,168 bytes
               3 Dir(s)  171,347,292,160 bytes free

C:\Users\James\Desktop>

不,这似乎不是权限问题。谁能解释这个printf 函数是如何绕过标准输出重定向过程的?

【问题讨论】:

  • 我的猜测是运行时库没有正常退出,虽然我不知道为什么。无论如何,如果这是问题所在,您可以通过显式刷新标准输出缓冲区或关闭缓冲来解决它。见stackoverflow.com/a/1716621/886887

标签: c++ windows printf stdout


【解决方案1】:

当程序出于某种原因退出时,输出缓冲区似乎没有被刷新。

return hr; 行之前添加fflush(stdout); 可以为我解决此问题。

我尝试了其他一些方法,例如将宽字符串转换为窄字符串并将其传递给 printf,使用 wprintf,编译为多字节并将字符串转换为窄字符串以传递给 printf,但只能手动刷新缓冲区。

【讨论】:

    【解决方案2】:

    我已尝试从您包含的链接下载项目文件并运行已构建并包含在 Release 文件夹中的可执行文件,它按预期工作。我还在 VC++2013 中重新构建了代码,并且也按预期工作。

    我怀疑是操作员错误或某些系统问题 - 但是,您问题中的信息似乎并不表明操作员错误;你提供了证据证明这不是个案。

    我从C:\Users\&lt;userprofile&gt;\Documents\Visual Studio 2013\test\Release 运行代码。 Desktop 是 Windows 中的一个“特殊”文件夹,虽然我对此表示怀疑,但它可能会有一些影响。不管怎样,我不认为这是一个编程问题。

    【讨论】:

    • 你能提供更多关于你的环境的信息吗?
    • @James:Windows 8.1,64 位,管理员权限。不知道您可能还需要知道什么。
    • Windows 7 Ultimate x64 以及提供的可执行文件和我构建的没有更改的可执行文件都不起作用。我编写/使用了很多控制台应用程序,以前从未见过这种行为。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-09
    • 2017-03-31
    相关资源
    最近更新 更多