gpt4 book ai didi

windows - 如何在 Windows 下将 stdout 和 stderr freopen() 到一个输出文件中

转载 作者:可可西里 更新时间:2023-11-01 10:32:09 25 4
gpt4 key购买 nike

我有一个 Windows Win32/GUI 应用程序,它有时会向 stdoutstderr 打印有趣的输出,所以我想做的是捕获该输出在应用程序退出后进入文件以供审查。

问题是,我可以成功调用 freopen_s()stdout 输出捕获到一个文件中,或者我可以用它来捕获stderr 输出到一个文件中,但尝试同时执行这两个操作只会产生一个包含经过处理的数据的截断文件。

下面是一个重现问题的简单程序;如果我注释掉两个 freopen_s() 调用中的任何一个,那么我会在创建的 blah.txt 文件中得到预期的输出(即两个文本之一行),但我想要以包含两个文本行的 blah.txt 结束。

在 Windows 下可以吗?我可以回过头来创建两个不同的文件(例如 blah_stdout.txtblah_stderr.txt),但我宁愿不这样做,因为那时我必须手动重建生成 std​​out 和 stderr 输出的相对顺序。

int main(int argc, char *argv[])
{
const char * outFileName = "blah.txt";
FILE * junk1 = NULL, junk2 = NULL;
if (freopen_s(&junk1, outFileName, "w", stdout) != 0) abort();
if (freopen_s(&junk2, outFileName , "w", stderr) != 0) abort();
printf("This text was printed to stdout and should appear in blah.txt\n");
fprintf(stderr, "This text was printed to stderr and should appear in blah.txt\n");
return 0;
}

最佳答案

“w”打开模式记录为

Opens an empty file for writing. If the given file exists, its contents are destroyed.

但即使是“w+”和“a”也失败了。

如果您使用的是带有 dup2 的 CRT,您可以这样做:

#include <io.h> // MS CRT

...

FILE * junk1 = NULL;
if (freopen_s(&junk1, outFileName, "w", stdout) != 0) abort();
_dup2(1, 2); // Assign stderr to same file as stdout

这段代码在我测试时将两行都写入了文件,但从评论中可以明显看出,情况可能并非总是如此。较旧版本的 Visual Studio 更有可能工作。

如果您愿意放弃所有可移植性,您也可以直接访问 FILE 对象 (struct _iobuf) 背后的结构 (_iob/ __iob_func) 并用其他文件中的值覆盖成员。这是 not possible in VS 2015 and later :

FILE Encapsulation: In previous versions, the FILE type was completely defined in <stdio.h>, so it was possible for user code to reach into a FILE and muck with its internals. We have refactored the stdio library to improve encapsulation of the library implementation details. As part of this, FILE as defined in is now an opaque type and its members are inaccessible from outside of the CRT itself.

关于windows - 如何在 Windows 下将 stdout 和 stderr freopen() 到一个输出文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50357704/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com