繁体   English   中英

用C / C ++拆分输出以进行重定向

[英]Split output in C/C++ for redirecting

假设我有类似的代码

#include <iostream>
using namespace std;

int main() {
    cout << "Redirect to file1" << endl;
    cout << "Redirect to file2" << endl;
    return 0;
}

我想将第一个输出重定向到file1,第二个输出重定向到file2。 那可能吗?

我认为在C中, fclose(stdout)并重新打开stdout可能有所帮助,但我不确定如何重新打开它或是否有效。

谢谢

更新:为什么?

我有一个程序A,它从用户读取输入并生成相应的输出。 现在我想检查它是否正确,我有一个程序B,它为A生成输入,以及正确的输出。 B将一次生成一组测试数据。 我将有成千上万的测试。

在我的机器上,一千次./B > ``mktemp a.XXX``比使用ofstream更好。 使用fstream数千次,我的硬盘灯疯狂闪烁。 但是在重定向到临时文件时却没有。

UPDATE2:

在C ++中,似乎当时的答案是cout沿着cerr

除了stderr ,我可以关闭stdout并重新打开它吗?

为什么不使用文件流? 这样,无论shell重定向如何,它都很有可能工作:

#include <fstream>
#include <fstream>
using namespace std;
// opeen files
ofstream file1 ( "file1");
ofstream file2 ( "file2");
//write
file1 << "Redirect to file1" << endl;
file2 << "Redirect to file2" << endl;
//close files
file1.close();
file2.close();

你可以使用cout AND cerr。

cout << "Redirect to file1" << endl;
cerr << "Redirect to file2" << endl;

cerr转到标准错误

您始终可以使用标准错误流来处理错误消息。

#include <iostream>
using namespace std;

int main() {
    cout << "Redirect to file1" << endl;
    cerr << "Redirect to file2" << endl;
}

例如,使用Windows [cmd.exe]命令解释程序和Visual C ++ cl编译器:

[D:\dev\test]
> 









[D:\dev\test]
> 
streams.cpp

[D:\dev\test]
> 

[D:\dev\test]
> 
Redirect to file1

[D:\dev\test]
> 
Redirect to file2

[D:\dev\test]
> _


编辑:添加彩色代码和粗体强调。

另一种方法是使用cout.rdbuf()如下所示:

#include <iostream>
#include <fstream>
using namespace std;

int main () {
    ofstream cfile1("test1.txt");
    ofstream cfile2("test2.txt");

    cout.rdbuf(cfile1.rdbuf());        
    cout << "Redirect to file1" << endl;

    cout.rdbuf(cfile2.rdbuf());        
    cout << "Redirect to file2" << endl; 

    return 0;
}

码:

#include <iostream>
using namespace std;

int main() {
    cout << "Redirect to file1" << endl;
    cerr << "Redirect to file2" << endl;
    return 0;
}

安慰:

test > 1.txt 2> 2.txt

1.TXT:

Redirect to file1

2.txt:

Redirect to file2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM