c++ - 在 Windows 上重定向标准输出/标准错误

标签 c++ c windows stdout stderr

我有一个 Windows GUI 应用程序,它使用第三方库将调试/错误信息打印到 stdout/stderr。我找到了许多将它们重定向到我的日志文件的解决方案。但是 4 个中只有 1.5 个按预期工作。我在 WinXP SP3 32 位上使用 VS 2008 SP1。我没有包括错误处理,但没有调用返回错误。

// First one:
SetStdHandle(STD_OUTPUT_HANDLE, (HANDLE)_get_osfhandle(_fileno(log_file.get_FILE())));
SetStdHandle(STD_ERROR_HANDLE, (HANDLE)_get_osfhandle(_fileno(log_file.get_FILE())));

printf("%s", "1 Test printf to cout!\n");
fprintf(stderr, "%s", "1 Test printf to cerr!\n");

std::cout << "1 Test print to cout!\n";
std::cerr << "1 Test print to cerr!\n";

fflush(stdout);
fflush(stderr);


// Second one:
_dup2(_fileno(log_file.get_FILE()), _fileno(stdout));
_dup2(_fileno(log_file.get_FILE()), _fileno(stderr));

printf("%s", "2 Test printf to cout!\n");
fprintf(stderr, "%s", "2 Test printf to cerr!\n");

std::cout << "2 Test print to cout!\n";
std::cerr << "2 Test print to cerr!\n";

fflush(stdout);
fflush(stderr);


// Third one:
std::ofstream out_stream(log_file.get_FILE());
std::cout.rdbuf(out_stream.rdbuf());
std::cerr.rdbuf(out_stream.rdbuf());

printf("%s", "3 Test printf to cout!\n");
fprintf(stderr, "%s", "3 Test printf to cerr!\n");

std::cout << "3 Test print to cout!\n";
std::cerr << "3 Test print to cerr!\n";

fflush(stdout);
fflush(stderr);


// Fourth one:
*stdout = *log_file.get_FILE();
*stderr = *log_file.get_FILE();

printf("%s", "4 Test printf to cout!\n");
fprintf(stderr, "%s", "4 Test printf to cerr!\n");

std::cout << "4 Test print to cout!\n";
std::cerr << "4 Test print to cerr!\n";

fflush(stdout);
fflush(stderr);

在我测试它们之后(当然是分开的),我得到了这些结果:
3 测试打印输出!
3 测试打印到 cerr!
4 测试printf到cout!
4 测试打印输出!
4 测试 printf 到 cerr!
4 测试打印到 cerr!

为什么只有最后一个解决方案完全有效?使用它安全吗?

更新。 XCode测试结果:
2 测试printf到cout!
2 测试打印输出!
2 测试 printf 到 cerr!
2 测试打印到 cerr!
4 测试printf到cout!
4 测试打印输出!
4 测试 printf 到 cerr!
4 测试打印到 cerr!
第一个显然仅适用于 Windows,第三个失败,因为没有采用 FILE* 参数的文件流构造函数。

最佳答案

最后:

  1. 您正在更改实际的 FILE pointer到标准输出和标准错误。显而易见的原因。 std::cout 和 std::cerr 最终将输出发送到这些指针。

  1. std::ios.rdbuf更改 stream,其中 std::ios 的实例(在本例中为 std::cout 和 std::cerr)发送它的流。

  1. 我从没听说过。我可能会做一些研究并编辑答案。

  1. 与 2 相同。

关于c++ - 在 Windows 上重定向标准输出/标准错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30891458/

相关文章:

c++ - OR (||) 运算符在 C++ 中无法正常工作

使用 C 中的 realloc 更改内存地址

c - 为什么编译器会假设这些看似相等的指针不同?

c - 循环 (char *c, ...)

windows - 如何使用正确的工作目录从 BAT 文件启动 PowerShell 脚本?

c++ - `const_iterator` 真的需要与 `iterator` 属于不同的类吗?

c++ - 指针不可从列表中取消引用

c++ - 为什么没有像 pthread_mutex_t & std::mutex 那样的 std::等价于 pthread_spinlock_t?

windows - 如何在后台运行 .exe,使用 perl PAR 的 pp 模块从 perl 脚本创建

windows - 没有 mac 的 iPad 开发