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.
With cerr, the output flushs immediately (because cerr does not use buffer). With clog, the output flushs after you finish your current function.
With cerr, the output flushs immediately (because cerr does not use buffer). With clog, the output flushs after you finish your current function. explicitly call the function flush. With cout, the output flushs after you have call to any output streams (cout, cerr, clog). after you finish your current function.
Buffered standard error stream (clog): This is also an instance of ostream class and used to display errors but unlike cerr the error is first inserted into a buffer and is stored in the buffer until it is not fully filled. Show activity on this post. The difference of these 3 streams is buffering. immediately (because cerr does not use buffer).
Un-buffered standard error stream (cerr): cerr is the standard error stream which is used to output the errors. This is also an instance of the ostream class. As cerr is un-buffered so it is used when we need to display the error message immediately. It does not have any buffer to store the error message and display later.
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).
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