Is it possible to use cout for terminal when redirecting cout to outfile?

I run the program and redirect coutto the outfile, for example:

./program < infile.in > outfile.o  

I want to be able to read options ("-h" or "--help") from the command line and display a help message on the terminal. Is there a way I can do this, but there is still regular coutfrom the rest of the program, go to outfile?

Would the coutright object be used for such a thing?

+5
source share
6 answers

cerr STDERR, outfile.o.

./program < infile.in > outfile.o:

cout << "This writes to STDOUT, and gets redirected to outfile.";
cerr << "This doesn't get redirected, and displays on screen.";

STDOUT STDERR,

./program < infile.in &> outfile.o

STDERR, STDOUT,

./program < infile.in 2> outfile.o

Bash redirection , , , ( " > " ).

+15

linux, - /dev/tty ( ). , stderr , stdout. .

.

#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

, , , , , , . .

+3

~$ cmd | tee log_file, stdout
~$ cmd 2>log_file stdout stderr

+2

stderr. Stderr , , .

+1

, - , - , - .

void write_out(ostream &o);

And then I can create Fstream objects and pass them or pass to cout and cerr everything I need at this time. This can be useful when writing a registration code, where sometimes you want to see what is happening on the terminal, and at other times you just need a log file.

NTN.

+1
source

You should use cerr instead of cout. Using shell redirection> only redirects stdout (cout), not stderr (cerr).

0
source

All Articles