How to set errno value?

JAN picture JAN · Jul 28, 2012 · Viewed 46.6k times · Source

I have two calls to two different methods :

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

  }

}

And the second method :

void func2() 
{
  // do something 
  if (fail) 
  {
    // then set errno to ENOENT

  }

}
  1. When I set the errno to some value , what does it do ? just error checking ?

  2. How can I set errno in the above methods func1 and func2 to EEXIST and ENOENT

Thanks

Answer

cnicutar picture cnicutar · Jul 28, 2012

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 ?