KarimS
KarimS

Reputation: 3902

Flags mask read and write posix

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

Upvotes: 3

Views: 4317

Answers (3)

hellmean
hellmean

Reputation: 131

I don't think the above answer given by @Duck here is correct. Given the examples it makes no sense to mask them.

The reason you need to mask is that

flags = fcntl(fd, F_GETFL);

returns more than just these two bits. In fact the return value could be something like this:

1000000000000001

for write only file.

We mask in order to get rid of those other bits, which are not related to the read/write permissions.

Upvotes: 2

Naveen H
Naveen H

Reputation: 1

In this O_ACCMODE is used as and mask to get access mode bits.

Upvotes: 0

Duck
Duck

Reputation: 27572

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.

Upvotes: 2

Related Questions