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;
}
}
}
access(directory, R_OK && W_OK)
should beaccess(directory, R_OK|W_OK)
. Also there is no reason to compute(stats.mode) & (0777)
; you can just usestats.mode
directly. That said, there is no functional difference between these approaches. – Panettone