1

Using the stat function, I can get the read/write permissions for:

  • owner
  • user
  • other

...but this isn't what I want. I want to know the read/write permissions of a file for my process (i.e. the application I'm writing). The owner/user/other is only helpful if I know if my process is running as the owner/user/other of the file...so maybe that's the solution but I'm not sure of the steps to get there.

user109078
  • 906
  • 7
  • 19

3 Answers3

2

Use getuid()/geteuid() to determine the process's user ID, and similarly getgid()/getegid() for the group ID. Then you can compare to the owner/group of the file (which you get from stat or lstat) and cross-reference the permission bits.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
2

You don't want to use stat() for this. You want to use access() from <unistd.h>:

char const* name = "file";
if (access(name, R_OK)) {
    std::cout << "'" << name << "' is readable\n";
}
if (access(name, W_OK)) {
    std::cout << "'" << name << "' is writable\n";
}
Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380
  • The problem with access() is that by the time the result is interpreted it might already by outdated (because another process changed the permissions). If one needs to read or write a file, the best way to check the permissions is to open it for reading or writing and see whether it works. – Seg Fault Sep 23 '12 at 21:42
  • I agree that the status may change the moment you have looked. The original question didn't state what it is meant to be used for. For example, it the goal is to create a list of files which can be potentially opened in a file selection dialog, it may not be practical to open all files because there tends to be a limit on the number of files which can be opened. – Dietmar Kühl Sep 23 '12 at 21:48
1

Something like this:

if ( access( filename, W_OK )) { /* writable */ }

See access(2).

Nikolai Fetissov
  • 82,306
  • 11
  • 110
  • 171