读书人

怎样才能把标准输入和标准异常同时重定

发布时间: 2013-08-04 18:26:16 作者: rapoo

怎样才能把标准输入和标准错误同时重定向到一个文件,这样看起来像是cmd的完整输出。。。
怎样才能把标准输入和标准错误同时重定向到一个文件,这样看起来像是cmd的完整输出。。。
code=c] if (freopen(shellFileName, "w", stdout)==NULL)
return 0;
if (freopen(shellFileName, "w", stderr)==NULL)
return 0;
//这样子还是好象只重定向了一个。。。
[/code]
[解决办法]
我只注意到2个头像不一样...
[解决办法]
没事别用stderr
[解决办法]
cmd >log 2>&1
[解决办法]
command &>filename 或者楼上那种
[解决办法]

#include <iostream>
#include <fstream>

int main()
{
ofstream ofs("output.txt");
streambuf *sb = ofs.rdbuf();

cout.ios::rdbuf(sb);
cerr.ios::rdbuf(sb);

cout << "cout" << endl;
cerr << "cerr" << endl;

return 0;
}

[解决办法]
The freopen() function opens the file whose name is the string pointed
to by path and associates the stream pointed to by stream with it. The
original stream (if it exists) is closed. The mode argument is used
just as in the fopen() function. The primary use of the freopen()
function is to change the file associated with a standard text stream


(stderr, stdin, or stdout).
所以第二次调用freopen的时候前一次调用的stream就关掉了。

这种场景一般用平台API,比如dup和dup2。
[解决办法]
简单点就


if (freopen("D:\\1.txt", "w", stdout)==NULL)
return 0;

*stderr = *stdout;

读书人网 >C语言

热点推荐