What is the difference between them and how are they used? Can anyone point me to examples?
Specifically, how do you "write" to the stream in both cases and how do you recover and output (i.e. to the screen) the text that had been written to it?
Also, the "screen" output is itself a stream right? Maybe I don't understand streams well enough. This can also be saved to a file of course, I know. Would all of these use fprintf
/ fscanf
, etc?
cerr – Standard Error Stream Object in C++ Standard error stream (cerr): cerr is the standard error stream which is used to output the errors. It is an instance of the ostream class.
Stderr, also known as standard error, is the default file descriptor where a process can write error messages. In Unix-like operating systems, such as Linux, macOS X, and BSD, stderr is defined by the POSIX standard. Its default file descriptor number is 2.
std::cerr is an object of class ostream that represents the standard error stream oriented to narrow characters (of type char). It corresponds to the C stream stderr. The standard error stream is a destination of characters determined by the environment.
cout is an object of the stdout stream, while cerr is an object of the stderr stream. stdout and stderr are different streams, even though they both refer to console output by default. Redirecting (piping) one of them (e.g. program.exe >out. txt) would not affect the other.
cerr
is the C++ stream and stderr
is the C file handle, both representing the standard error output.
You write to them the same way you write to other streams and file handles:
cerr << "Urk!\n"; fprintf (stderr, "Urk!\n");
I'm not sure what you mean by "recover" in this context, the output goes to standard error and that's it. The program's not meant to care about it after that. If you mean how to save it for later, from outside the program, see the next paragraph.
By default, they'll go to your terminal but the output can be redirected elsewhere with something like:
run_my_prog 2>error.out
And, yes, the "screen" output is a stream (or file handle) but that's generally only because stdout/cout
and stderr/cerr
are connected to your "screen" by default. Redirection will affect this as in the following case where nothing will be written to your screen:
run_my_prog >/dev/null 2>&1
(tricky things like writing directly to /dev/tty
notwithstanding). That snippet will redirect both standard output and standard error to go to the bit bucket.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With