Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get error message for errno value (C language)?

Tags:

c

c89

How can I get error message for errno value (C language)? For example, I can write such file (errno_messages.h):

#include <errno.h>

char* get_errno_message(void){
    switch (errno) {
    case 0:
        return "";
        break;
    case EPERM:
        return "Operation not permitted";
        break;
    case ENOENT:
        return "No such file or directory";
        break;
    case ESRCH:
        return "No such process";
        break;
        /* e.t.c. */
    default:        
        break;
    }
}

But maybe such function is exists already?

Best Regards

like image 873
Andrey Bushman Avatar asked Sep 30 '12 16:09

Andrey Bushman


People also ask

How does errno work in C?

Global Variable errno: When a function is called in C, a variable named as errno is automatically assigned a code (value) which can be used to identify the type of error that has been encountered. Its a global variable indicating the error occurred during any function call and defined in the header file errno. h.

What type is errno in C?

errno is defined by the ISO C standard to be a modifiable lvalue of type int, and must not be explicitly declared; errno may be a macro. errno is thread-local; setting it in one thread does not affect its value in any other thread.

Where is errno declared?

The errno is defined in cerrno header file.


2 Answers

I think what you're looking for is strerror().

like image 63
Joachim Isaksson Avatar answered Oct 11 '22 14:10

Joachim Isaksson


Aside of strerror(), a useful function is perror that also directly prints the error out with a given prefix. Often, you will want to do something like

int fd = open(filename, O_READ);
if (fd < 0) {
  perror(filename);
  exit(EXIT_FAILURE);
}
like image 38
Petr Baudis Avatar answered Oct 11 '22 15:10

Petr Baudis