vendredi 10 juin 2016

What is the most concise way to ascertain whether the program itself has a certain access right to a file?


Note that for the purpose of this question I will assume that a directory is a special kind of file.

Furthermore, I will assume (and please do correct me if I am wrong), that writing rights to a directory encompass the right to create new files within said directory.

std::filesystem::perms lists the following kinds of permission, each for the three operation types read, write and execute:

  • owner : The owner of the file.
  • group : The user group of the file.
  • others: Everyone? (Not at all sure about that; please correct if wrong.)

Now, as can easily be seen, if one wishes to know whether the running program has a given right, this information is non-trivial to derive from these:

  • Is the program's user the file's user?
  • Is any of the file's user group one of or a child of the program's user group?

Interestingly, there does not seem to exist any function in the library, which would correspond to the following function declaration:

enum FileAction { READ = 1, WRITE = 2, RW = READ|WRITE };

bool canDo(const std::filesystem::path & path, FileAction action);

How could such a function be implemented then?

Of course, the good old pre-C++17 way would be to just try and start reading/writing and catch the exception if it fails. I would like to think that the Filesystem library has to offer a more elegant solution.

I am interested in answers applicable to Windows (XP+) and Linux. Please remark, if your answer only applies to one (even if one should hope that a universal answer does exist and can be found).


addendum: As the first few answers seem to go in a direction I have neither anticipated nor intended, let me clarify further:

I feel no desire to check for mechanical failure and consider it a notably different class of error, if access may very well be possible but is merely denied.

Furthermore, it can be assumed that a running application will not have rights it did not have moments ago, just as it can be assumed that a running application will still have the rights it had moments ago. This assumption can probably not hold for long-running programs such as service daemons, but this is not my use case here.

I also find it much more informative if the following state is reached: I am allowed to read a file but cannot seem to do so than merely The file cannot be read.

In the former case the program can ask the user for elevated rights early. In the latter case the program may do the same... as a false-negative, because e.g. the drive holding the file is gone.

In any case, the assumption that I have access now translates into I will have access later can be upheld unless more pressing issues (hardware failure, third-party incursion, what-have-you) exist and it's no longer expected of the program to behave in a well-defined manner.


Aucun commentaire:

Enregistrer un commentaire