Issue
Checking the access mode of the file is slightly more complex, since the O_RDONLY (0), O_WRONLY (1), and O_RDWR (2) constants don’t correspond to single bits in the open file status flags. Therefore, to make this check, we mask the flags value with the constant O_ACCMODE, 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 flags & O_ACCMODE work
Sorry for bad formatting i'm writing from my phone
Solution
The file modes are mutually exclusive. You can't be read-only and write-only, and you can't be read-write and either of the other two.
O_ACCMODE is equal to 3 so bits 1 and 2 are on.
00000000 (O_RDONLY)
& 00000011 (O_ACCMODE)
--------
00000000 <-- the result being compared
where 00000000 equals read-only so (accessMode == O_RDONLY) returns true.
The same for the others.
00000001 (O_WRONLY)
& 00000011 (O_ACCMODE)
---------
00000001 <-- the result being compared
O_WRONLY is 1 so (accessMode == O_WRONLY) is "is 1 equal to 1" which naturally returns true.
Answered By - Duck Answer Checked By - David Marino (WPSolving Volunteer)