简体   繁体   English

条件(类型 & ~(R_OK|W_OK|X_OK|F_OK))在 C 中如何工作?

[英]How does the condition (type & ~(R_OK|W_OK|X_OK|F_OK)) work in C?

What kind of condition is used here and how does it works in C?这里使用了什么样的条件,它在 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 https://code.woboq.org/userspace/glibc/io/access.c.html

The expression uses bitwise arithmetic .该表达式使用按位算术

a | b | c … a | b | c … creates a value that has all the bits of a , b , c … set. a | b | c …创建一个包含abc ... 的所有位的值。

In your piece of code, R_OK etc. are bit flags that each have a single, distinct bit set.在您的代码中, R_OK等是位标志,每个标志都有一个不同的位集。 Their disjunction (= or-ing them together) thus has all their bits set, and none other.因此,它们的析取(= 或将它们组合在一起)设置了所有位,而没有其他位。

~ x inverts the bits of a value. ~ x反转一个值的位。 Thus, the result of the operation has all bits set except those of R_OK etc.因此,操作的结果除了R_OK等之外的所有位都设置了。

Finally, a & b sets only those bits which are set in both a and b .最后, a & b仅设置ab中设置的那些位。 All other bits will be 0.所有其他位将为 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.因此,该表达式一起测试变量type是否设置了任何R_OK等定义的位。换句话说:它测试test的值是否是R_OK等之一,或这些值的组合。 If that is not the case (ie if it has some other value), the test fails.如果不是这种情况(即,如果它具有其他值),则测试失败。

The function you've posted thus test whether it has received valid arguments (ie that file is not NULL , and that test is a valid combination of supported flags).您发布的 function 因此测试它是否收到有效的 arguments (即该file不是NULL ,并且该test是受支持标志的有效组合)。 Beyond this, the function does nothing except set an error status and return -1.除此之外,function 除了设置错误状态并返回 -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.这种奇怪行为的原因可以在最后一行看到:您发布的 function 是一个存根,它实际上并没有实现正确的 POSIX access function。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM