问题
I am dealing with file status flags. Among test I performed, I found
#include <stdio.h>
#include "fcntl.h"
int main() {
const int flag = O_RDONLY;
printf( "*** Flag O_RDONLY = %5d\n", flag);
return 0;
}
produces this output
*** Flag O_RDONLY = 0
which is fully consistent with
#define O_RDONLY 00
from fcntl-linux.h
.
How can the value zero be used as a flag?
I expect an "atomic" flag to be 2^n
(n>=1
), and "composite" flags (like O_ACCMODE
) to be simply the sum of several atomic flags (which is the same as bitwise-or'ing those atomic flags).
As far as I understand, I cannot "detect" anything, and such flag cannot be ever set.
A bitwise-and'ed expression like (stat & O_RDONLY)
will always be false.
Related:
How to get the mode of a file descriptor? (I asked this)
回答1:
Although these are called flags in the documentation, these three are not actually atomic flags that can be combined like the rest. They're mutually exclusive alternative values for the O_ACCMODE
bits. You don't use stat & RDONLY
to test for it, you use (stat & O_ACCMODE) == O_RDONLY
.
来源:https://stackoverflow.com/questions/61923703/how-to-make-sense-of-o-rdonly-0