Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for writing permissions to file in Windows/Linux

I would like to know how to check if I have write permissions to a folder.

I'm writing a C++ project and I should print some data to a result.txt file, but I need to know if I have permissions or not.

Is the check different between Linux and Windows? Because my project should run on Linux and currently I'm working in Visual Studio.

like image 494
Aviadjo Avatar asked Sep 26 '10 17:09

Aviadjo


People also ask

How do I check permissions on a file in Linux?

To view the permissions for all files in a directory, use the ls command with the -la options. Add other options as desired; for help, see List the files in a directory in Unix. In the output example above, the first character in each line indicates whether the listed object is a file or a directory.


1 Answers

The portable way to check permissions is to try to open the file and check if that succeeded. If not, and errno (from the header <cerrno> is set to the value EACCES [yes, with one S], then you did not have sufficient permissions. This should work on both Unix/Linux and Windows. Example for stdio:

FILE *fp = fopen("results.txt", "w");
if (fp == NULL) {
    if (errno == EACCES)
        cerr << "Permission denied" << endl;
    else
        cerr << "Something went wrong: " << strerror(errno) << endl;
}

Iostreams will work a bit differently. AFAIK, they do not guarantee to set errno on both platforms, or report more specific errors than just "failure".

As Jerry Coffin wrote, don't rely on separate access test functions since your program will be prone to race conditions and security holes.

like image 61
Fred Foo Avatar answered Nov 09 '22 05:11

Fred Foo