What are “cerr” and “stderr”?

旧街凉风 提交于 2019-12-20 17:36:28

问题


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?


回答1:


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.




回答2:


What is the difference between them

stderr is a FILE*, and part of the standard C library. cerr is an ostream, and part of the standard C++ library.

Also, the "screen" output is itself a stream right?

Yes, it is. But there are actually two streams that write to the screen by default: stdout/cout is for normal output and stderr/cerr is for error messages. This is useful for redirection: You can redirect stdout to a file but still have your error messages on the screen.



来源:https://stackoverflow.com/questions/3200117/what-are-cerr-and-stderr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!