7

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?

Community
  • 1
  • 1
poy
  • 10,063
  • 9
  • 49
  • 74
  • @Erik: Yes!... I saw that function before, I just couldn't come up with it again. Thanks! – poy Apr 12 '11 at 20:04

2 Answers2

15

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.

Erik
  • 88,732
  • 13
  • 198
  • 189
5

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;
phs
  • 10,687
  • 4
  • 58
  • 84
luis.espinal
  • 10,331
  • 6
  • 39
  • 55