Вопрос

I got a program which contains a lot of std::cerr, it directly outputs to my terminal. I am wondering what is the difference between std::cerr and std::cout. And how can I disable the std::cerr (I don't want it output to my screen)?

Это было полезно?

Решение

As others have mentioned, if this is a Unix-like system then 2>/dev/null redirects stderr (2) to the big bit bucket in the sky (/dev/null).

But nobody here has explained what the difference between stderr and stdout is, so I feel obligated to at least touch on the topic.

std::cout is the standard output stream. This is typically where your program should output messages.

std::cerr is the standard error stream. This is usually used for error messages.

As such, if your program "contains lots of cerr" output, then it might be worth taking a look at why so many error messages are being printed, rather than simply hiding the messages. This is assuming, of course, that you don't just happen to have a program that emits lots of non-error output to stderr for some reason.

Другие советы

Assuming this program is executed on a *nix system, one possibility is to redirect stderr to /dev/null.

This old newsgroup post shows how to redirect. (code is too large to post here). You need to use streambuf* rdbuf.

cerr is an object of class ostream that represents the standard error stream. It is associated with the cstdio stream stderr.

By default, most systems have their standard error output set to the console, where text messages are shown, although this can generally be redirected.

Because cerr is an object of class ostream, we can write characters to it either as formatted data using for example the insertion operator (ostream::operator<<) or as unformatted data using the write member function, among others (see ostream).

2>/dev/null does the trick. Once again I need to make up the 30 characters.

In many systems, including Windows and Unixes, there are two standard output streams: stdout and stderr.

Normally, a program outputs to stdout, which can be either displayed on screen, or redirected to a file: program > output.txt or redirected as input for another program program1 | program2. For example, you can search in output of your program with the grep tool by running program | grep searchword.

However, if an error occurs, and you print it to stdout which is redirected, the user won't see it. That's why there is the second output for errors. Also the user usually doesn't want error text to be written to the output file, or be fed to grep.

When running a program, you can redirect its error output to a file with program 2>file. The file can be /dev/null, or &1, which would mean redirect to stdout.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top