C++ 将cout重定向到outfile时是否可以将cout发送到终端?
我正在运行一个程序,并将C++ 将cout重定向到outfile时是否可以将cout发送到终端?,c++,bash,shell,redirect,cout,C++,Bash,Shell,Redirect,Cout,我正在运行一个程序,并将cout重定向到一个输出文件,如下所示: ./program < infile.in > outfile.o /programoutfile.o 我希望能够从命令行读入选项('-h'或'-help'),并向终端输出帮助消息。是否有一种方法可以做到这一点,但仍然让程序其余部分的常规cout转到outfile cout是用于这种事情的正确对象吗?你应该使用cerr而不是cout。使用shell重定向>仅重定向标准输出(cout),而不重定向标准输出(cer
cout
重定向到一个输出文件,如下所示:
./program < infile.in > outfile.o
/programoutfile.o
我希望能够从命令行读入选项('-h'或'-help'),并向终端输出帮助消息。是否有一种方法可以做到这一点,但仍然让程序其余部分的常规cout
转到outfile
cout
是用于这种事情的正确对象吗?你应该使用cerr而不是cout。使用shell重定向>仅重定向标准输出(cout),而不重定向标准输出(cerr)。您可能希望将帮助消息输出到标准输出。STDRR通常用于非正常输出,您可以考虑使用段落是这样的输出。< P> <代码> ~$$CMD > Logyfile 到DUP <代码> STDUD/<代码>文件和终端> BR>
~$cmd 2>log_file
要将stdout
打印到终端上,并将stderr
打印到一个文件中您应该使用cerr将帮助消息输出到stderr,它不包括在重定向到outfile.o的过程中
给定/programoutfile.o
:
cout << "This writes to STDOUT, and gets redirected to outfile.";
cerr << "This doesn't get redirected, and displays on screen.";
cout outfile.o
它比大多数人意识到的要复杂得多,通常除了最简单的形式(“>”)之外的所有内容都会被忽略。我做过的一件事——并不是说这总是合适的——就是编写具有类似此签名的模块
void write_out(ostream &o);
然后我可以创建fstream对象并将它们传入,或者传入cout和cerr,当时我需要做的任何事情。这对于编写日志代码很有帮助,有时您希望在终端上看到发生了什么,有时您只需要一个日志文件
HTH.如果您在linux上,您可以使用伪设备
/dev/tty
输出到控制终端(如果有)。即使重定向了stderr
以及stdout
,这也会起作用。其他操作系统可能提供类似的机制
例如
#包括
#包括
#包括
int main()
{
std::流术语(“/dev/tty”,std::ios_base::out);
学期
./program < infile.in 2> outfile.o
void write_out(ostream &o);
#include <iostream>
#include <ostream>
#include <fstream>
int main()
{
std::ofstream term("/dev/tty", std::ios_base::out);
term << "This goes to terminal\n";
std::cout << "This goes to stdout\n";
return 0;
}
$ ./a.out
This goes to stdout
This goes to terminal
$ ./a.out >/dev/null
This goes to terminal