How to set errno value?

前端 未结 3 1295
借酒劲吻你
借酒劲吻你 2020-12-29 03:12

I have two calls to two different methods :

void func1() 
{
  // do something 
  if (fail) 
  {
    // then set errno to EEXIST

  }

}

An

相关标签:
3条回答
  • 2020-12-29 03:37
    #include <errno.h>
    void func1() 
    {
      // do something 
      if (fail) 
      {
        errno = ENOENT;
      }
    }
    
    0 讨论(0)
  • 2020-12-29 03:44

    IMO, the standard errno designed for system level. My experience is do not pollute them. If you want to simulate the C standard errno mechanism, you can do some definition like:

    /* your_errno.c */
    __thread int g_your_error_code;
    
    /* your_errno.h */
    extern __thread int g_your_error_code
    #define set_your_errno(err) (g_your_error_code = (err))
    #define your_errno (g_your_error_code)
    

    and also you can still implement your_perror(err_code). More information, please refer to glibc's implementation.

    0 讨论(0)
  • 2020-12-29 03:48

    For all practical purposes, you can treat errno like a global variable (although it's usually not). So include errno.h and just use it:

    errno = ENOENT;
    

    You should ask yourself if errno is the best error-reporting mechanism for your purposes. Can the functions be engineered to return the error code themselves ?

    0 讨论(0)
提交回复
热议问题