如何将stdout和stderr重定向到c ++中的单个文件?
我试过的是:if((LogStream = freopen(strFilePath.c_str(), "w", stdout)) == NULL)
{
cout << "Failed to redirect console logs\n";
}
if((LogStream = freopen(strFilePath.c_str(), "a", stderr)) == NULL)
{
cout << "Failed to redirect console logs\n";
}
但它没有按照我的预期运作。
提前致谢
答案 0 :(得分:3)
以下是如何更改每个原始文件/ C缓冲文件/ C ++缓冲流:
#include <unistd.h>
#include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;
int main() {
// unbuffered system-call level write() access:
::fclose(stderr);
if (::dup2(STDOUT_FILENO, STDERR_FILENO) == -1) {
cout << "dup2() failed!" << endl;
return -1;
}
char msg_err[] = "write(STDERR_FILENO) OK.\n";
char msg_out[] = "write(STDOUT_FILENO) still OK.\n";
write(STDERR_FILENO, msg_err, strlen(msg_err));
write(STDOUT_FILENO, msg_out, strlen(msg_out));
// buffered C-style access: (ordering may be weird w/o fflush())
stderr = ::fdopen(STDOUT_FILENO, "a");
fprintf(stderr, "fprintf(stderr) OK.\n");
fprintf(stdout, "fprintf(stdout) still OK.\n");
// buffered C++ access:
std::cerr.rdbuf(std::cout.rdbuf());
cerr << "cerr << OK.\n";
cout << "cout << still OK.\n";
}
也就是说,从调用shell中执行此操作仍然更好。