Home > Back-end >  How does the condition (type & ~(R_OK|W_OK|X_OK|F_OK)) work in C?
How does the condition (type & ~(R_OK|W_OK|X_OK|F_OK)) work in C?

Time:01-06

What kind of condition is used here and how does it works in C?

(type & ~(R_OK|W_OK|X_OK|F_OK))

Found it here.

/* Test for access to FILE.  */
int
__access (const char *file, int type)
{
  if (file == NULL || (type & ~(R_OK|W_OK|X_OK|F_OK)) != 0)
    {
      __set_errno (EINVAL);
      return -1;
    }
  __set_errno (ENOSYS);
  return -1;
}
stub_warning (access)

https://code.woboq.org/userspace/glibc/io/access.c.html

CodePudding user response:

The expression uses bitwise arithmetic.

a | b | c …  creates a value that has all the bits of a, b, c … set.

In your piece of code, R_OK etc. are bit flags that each have a single, distinct bit set. Their disjunction (= or-ing them together) thus has all their bits set, and none other.

~ x inverts the bits of a value. Thus, the result of the operation has all bits set except those of R_OK etc.

Finally, a & b sets only those bits which are set in both a and b. All other bits will be 0.

The expression, taken together, thus tests whether the variable type has any bits set which are not defined by R_OK etc. In other words: it tests whether test’s value is one of R_OK etc., or a combination of these values. If that is not the case (i.e. if it has some other value), the test fails.

The function you’ve posted thus test whether it has received valid arguments (i.e. that file is not NULL, and that test is a valid combination of supported flags). Beyond this, the function does nothing except set an error status and return -1. And the reason for this weird behaviour can be seen in the last line: the function you’ve posted is a stub, it does not actually implement a proper POSIX access function.

  •  Tags:  
  • Related