0

In C++ is there a way to check, if we have the permission to create a file at a certain path without actually creating a file? I already read How do I create a file with boost filesystem without opening it

Here is how we can do it by creating the file, which in my case is not an optimal solution.

std::ofstream file;
file.open(path, std::ios_base::app);
if (!file.is_open()) {
   WARNING("Unable to create file ");
   return false;
}
file.close();

P.s. I have even tried to check permission for every file but I feel there must be a better solution to it. How to get file permissions with c++ boost library?

Abhinav
  • 11
  • 3
  • Can you check the permissions of the folder the file's going into to see who is allowed to write a new file? – user4581301 Feb 04 '21 at 19:01
  • 2
    Lots of edge cases with a file or directory that may already exist with the same name. Also you would probably have to do all the OS specific checks regarding full path traversal as well. Faster, easier and guaranteed to be correct to just attempt to create the file and if successful immediately delete it. – Richard Critten Feb 04 '21 at 19:05
  • @user4581301 Yes, that could be a better solution than what I have actually done in many other cases. Thank you for the suggestions. But in my case, it would not be optimal as the path changes frequently and the problem boils down to the same. – Abhinav Feb 04 '21 at 20:57
  • 2
    @Abhinav: The short answer is that (regardless of language you use) there's no dependable way to do this. Attempting to determine the result ahead of time is subject to a race condition, so even if you could do the check reliably, by the time you try to use the result, permissions may have changed so the answer is stale. – Jerry Coffin Feb 04 '21 at 21:00
  • @RichardCritten thank you. – Abhinav Feb 04 '21 at 21:08
  • 1
    @JerryCoffin Totally agreed, I was not even looking in that direction. You might have saved a bug or two. :D Thank you – Abhinav Feb 04 '21 at 21:09

0 Answers0