Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the C++ stream equivalent to perror? [duplicate]

Tags:

c++

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?

like image 555
poy Avatar asked Apr 12 '11 19:04

poy


People also ask

What does perror do in C?

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.

What is the difference between perror and printf?

But perror() writes to stderr while printf() writes to stdout . So, to print errors why is perror() used when printf() can do it.


2 Answers

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.

like image 185
Erik Avatar answered Oct 11 '22 09:10

Erik


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;
like image 33
luis.espinal Avatar answered Oct 11 '22 09:10

luis.espinal