Bamerza Bamerza - 29 days ago 12
C++ Question

File stat() vs access() to check permissions on a directory

I have successfully used both

stat()
&
access()
separately to determine if a user has either read or read/write access to a directory.

My question is:
- Is there a preferred method ? I see a lot of examples using
stat
, but for my purpose, access seems to be more lightweight and serves purpose.

- Are there any issues (e.g. - security) w/ one or the other ?
- Any issues w/ my approach ?

Here is some pseudo code (re-creating from memory w/o compiling) :

// Using access():
bool readAccessPermission = false;
bool writeAccessPermission = false;

if (mode == 'r'){
if (access(directory, R_OK) == 0)
readAccessPermission = true;
}
else{
if (access(directory, R_OK && W_OK) == 0)
readAccessPermission = true;
writeAccessPermission = true;
}


// vs. using stat function
// assume I already called stat(directory) and have the object


bool readAccessPermission = false;
bool writeAccessPermission = false;

var retmode = ((stats.mode) & (0777));

if (modeString == 'r'){
if ((retmode) & (consts.S_IRUSR)){
readAccessPermission = false;
}
}
else{
if ((retmode) & (consts.S_IRUSR)){
readAccessPermission = true;

if ((retmode) & consts.S_IWUSR)){
writeAccessPermission = true;
}
}
}

Answer

Either is equivalent for your needs. access() is a cleaner wrapper if you're not going to do anything with the stat structure that you populate.

Just be mindful that you are creating a race when doing this. The permissions can change between calling stat()/access() and when you actually try and use the directory. Hell, the directory could even be deleted and recreated in that time.

It's better to just try and open what you need and check for EPERM. Checking stat() or access() will not guarantee that a subsequent operation won't return EPERM.