tags:

views:

234

answers:

3

Can anybody explain the difference between cerr cout and clog and why does different objects are proposed?

I know the differences are as below:

1) cout can redirected but cerr can't

2) clog can use buffer.

I am confused about the point 2, I am grateful if anybody can elaborate it more.

+1  A: 

Both can be redirected.
On most implementations cerr wouldn't be buffered, not sure if this is an official POSIX requirement, but it's crazy to have a buffered error stream.

The reason for having separate streams is from the unix philosophy that the output of one program is the input to the next. If 'ls' is going straight to 'sort' it's easier to have errors appear on the console than have to write sort to understand if an input is an error message or part of the text you wish to sort.

Martin Beckett
+2  A: 

Buffered output is typically much faster than unbuffered. So if you wanted to write a vast amount of data quickly to a log (but didn't care if it actually ended up there), you would use clog rather than cerr.

And all streams can normally be redirected, assuming a vaguely competent operating system, but this is outwith the C++ standard, which has no such concept as "redirection".

anon
You may want to elaborate a bit on the upside of cerr/non-buffered-io's upside - i.e. the stream is written even if something wrong happens right after the write operation.
RaphaelSP
@RaphaelSP That's what I meant by "(but didn't care if it actually ended up there)"
anon
@Neil: the OP being seemingly confused about what buffering is, I think the formulation could be clearer :)
RaphaelSP
+2  A: 

Output can be buffered or unbuffered. With buffered output, the implementation saves up all the output until it's convenient to write it to disk (or wherever). This is nice and efficient, but if the program crashes some output will very likely be lost. The implementation has to write unbuffered output to disk as it occurs, which can slow things down with lots of disk writes, but unless there's a program crash while it's being written it will be written to disk.

There's no real functional difference between standard output and standard error; they're just two different output streams that can be redirected separately. The Unix philosophy of chaining tools together is that standard output will have the appropriate output to go into the input of the next tool, and this pretty much requires that there be a separate stream for error messages.

So, cout writes to standard output, and is buffered. Use this for normal output. cerr writes to the standard error stream, and is unbuffered. Use this for error messages. clog writes to the standard error stream, but is buffered. This is useful for execution logging, as it doesn't interfere with standard output, but is efficient (at the cost that the end of the log is likely to be lost if the program crashes).

David Thornley