2012-11-12 66 views
2

想我已经得到了我的代码要改向第一输出到file1和第二到file2。那可能吗?分割输出重定向像</p> <pre><code>#include <iostream> using namespace std; int main() { cout << "Redirect to file1" << endl; cout << "Redirect to file2" << endl; return 0; } </code></pre> <p>

我认为在C,fclose(stdout)和重新打开stdout可能会帮助,但我不知道如何重新打开它或它是否工作。

谢谢

更新:什么?

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

在我的机器上,千次./B > ``mktemp a.XXX``比使用ofstream的效果更好。数千次使用fstream,我的硬盘驱动器指示灯闪烁。但不是在重定向到临时文件时。

UPDATE2:

在C++中,似乎当时的回答是cerr一起cout

C怎么样,除了stderr,我可以关闭stdout并重新打开吗?

+1

在POSIX(Linux的/ OSX/BSD)外壳可以重定向'stdout'和'stderr'不同。这是你通过使用'std :: cout'和'std :: cerr'来完成的唯一方法。在Windows控制台中,我不认为这是可能的。另外,您不能将旧的C stdio函数与C++流混合。 –

+0

@Pileborg谢谢。如果我'fclose(stdout)''有没有办法重新打开'stdout'?在Linux中说,我可以使用'fopen(...)'重新打开'stdout'吗?它有什么参数?谢谢 – gongzhitaao

+0

这是可能的,但涉及知道它首先连接的TTY设备,并且您可能必须使用“open”系统调用,然后使用“fdopen”。 –

回答

1

您可以随时使用标准错误流用于例如错误消息。

#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] 
>type con >streams.cpp 
#include <iostream> 
using namespace std; 

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

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

[D:\dev\test] 
>streams 1>a.txt 2>b.txt 

[D:\dev\test] 
>type a.txt 
Redirect to file1 

[D:\dev\test] 
>type b.txt 
Redirect to file2 

[D:\dev\test] 
> _ 


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

+0

非常感谢,我只能接受一个答案=)请参阅我的update2。 – gongzhitaao

3

为什么不使用文件流?这样一来就会不管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(); 
+0

相当复杂的解释。我会更新我的问题以提供背景。 – gongzhitaao

2

您可以使用cout和cerr。

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

CERR转至标准错误

+0

非常感谢。请参阅我的更新2。 – gongzhitaao

1

另一种方式做它用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; 
} 
+0

没有'ofstream'。成千上万的'流'似乎给我的硬盘带来了沉重的负担。 – gongzhitaao

1

代码:

#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 
+0

非常感谢,我只能接受一个答案= P。请参阅我的问题update2。 – gongzhitaao

相关问题