Possible Duplicate:
C++ alternative to perror()
I can't find the stream equivalent to perror
. Is there such a thing? I like the fact that I can call:
perror("Error");
And it will fill in what errno
is. Can I do this with streams?
The perror() function displays the description of the error that corresponds to the error code stored in the system variable errno . errno is a system variable that holds the error code referring to the error condition. A call to a library function produces this error condition.
But perror() writes to stderr while printf() writes to stdout . So, to print errors why is perror() used when printf() can do it.
To print an error message:
str << strerror(errno);
If you're talking about the streams error state - no you can't get an automatic meaningful error message for that.
Since perror
writes to stderr, any equivalent in C++ has to do exactly the same. That is, it is not sufficient to write strerror(errno)
to a stream. The stream itself should (I'd say must) be a stream to standard error.
The following code snippet/pseudo code should give you an idea:
// depending on your compiler, this is all you need to include
#include <iostream>
#include <string.h>
#include <errno.h>
... somewhere in your code...
std::cerr << "Error: " << strerror(errno) << std::endl;
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