Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use errno in C++

I cannot understand what the errno library in c++ is for? What types of errors are set in it and how do I know which number stands for which error?

Does it affect program execution?

like image 589
Cool_Coder Avatar asked Oct 26 '11 09:10

Cool_Coder


1 Answers

errno.h is part of the C subset of C++. It is used by the C library and contains error codes. If a call to a function fails, the variable "errno" is set correspondingly to the error.

It will be of no use if you're using the C++ standard library.

In C you have functions that translate errno codes to C-strings. If your code is single threaded, you can use strerror, otherwise use strerror_r (see http://www.club.cc.cmu.edu/~cmccabe/blog_strerror.html)

For instance in C it works like this:

 int result = call_To_C_Library_Function_That_Fails();

 if( result != 0 )
 {
    char buffer[ 256 ];
    strerror_r( errno, buffer, 256 ); // get string message from errno, XSI-compliant version
    printf("Error %s", buffer);
     // or
    char * errorMsg = strerror_r( errno, buffer, 256 ); // GNU-specific version, Linux default
    printf("Error %s", errorMsg); //return value has to be used since buffer might not be modified
    // ...
 }

You may need it of course in C++ when you're using the C library or your OS library that is in C. For instance, if you're using the sys/socket.h API in Unix systems.

With C++, if you're making a wrapper around a C API call, you can use your own C++ exceptions that will use errno.h to get the corresponding message from your C API call error codes.

like image 153
Nikko Avatar answered Oct 03 '22 18:10

Nikko