Tag mask reads and writes posix
Checking the access pattern of a file is slightly more complicated because the O_RDONLY (0), O_WRONLY (1), and O_RDWR (2) constants do not correspond to individual bits in the open file status flag. So, for this check, we take the constant O_ACCMODE mask flag value and then test for equality with one of the constants:
accessMode = flags & O_ACCMODE; if (accessMode == O_WRONLY || accessMode == O_RDWR) printf("file is writable\n");
I want to understand how the expressiin flag and O_ACCMODE work
Sorry, I wrote it in the wrong format on my phone
File patterns are mutually exclusive. You cannot be read-only and write-only, nor can you be read-write or one of the other.
O_ACCMODE equals 3, so bits 1 and 2 open.
00000000 (O_RDONLY) & 00000011 (O_ACCMODE) -------- 00000000 <-- the result being compared
where 00000000 equals read-only, so (accessMode == O_RDONLY) returns true.
The same goes for the others.
00000001 (O_WRONLY) & 00000011 (O_ACCMODE) --------- 00000001 <-- the result being compared
O_WRONLY is 1,
so (accessMode == O_WRONLY) is “1 equals 1”, which naturally returns true.