Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ alternative to perror()

Tags:

I know we can use

perror()

in C to print errors. I was just wondering if there is a C++ alternative to this, or whether I have to include this (and therefore stdio.h) in my program. I am trying to avoid as many C functions as possible.

like image 953
Sagar Avatar asked Jul 23 '10 17:07

Sagar


People also ask

Where is strerror defined?

[edit] Defined in header <cstring> char* strerror( int errnum ); Returns a pointer to the textual description of the system error code errnum , identical to the description that would be printed by std::perror().

What is the difference between perror and strerror?

The function strerror() is very similar to perror(), except it returns a pointer to the error message string for a given value (you usually pass in the variable errno.) strerror() returns a pointer to the error message string.

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.


1 Answers

You could do something like:

std::cerr << strerror(errno) << std::endl;

That still ends up calling strerror, so you're really just substituting one C function for another. OTOH, it does let you write via streams, instead of mixing C and C++ output, which is generally a good thing. At least AFAIK, C++ doesn't add anything to the library to act as a substitute for strerror (other than generating an std::string, I'm not sure what it would change from strerror anyway).

like image 88
Jerry Coffin Avatar answered Sep 18 '22 17:09

Jerry Coffin