views:

44

answers:

3

hello, i would like to know how can i check if i have write permissions to folder.

i'm writing a c++ project and i should print some data to a result.txt file. and i need to know if i have permissions or not.

is the check deferent between linux and windows ? because my project finally should run on linux and currently i'm working on visual studio.

thanks allot.

+2  A: 

About the only reasonable thing to do is try to create the file, and if it fails, tell the user there was a problem. Any attempt at testing ahead of time, and only trying to create the file if you'll be able to create and write to it is open to problems from race conditions (had permission when you checked, but it was removed by the time you tried to use it, or vice versa) and corner cases (e.g., you have permission to create a file in that directory, but attempting to write there will exceed your disk quota). The only way to know is to try...

Jerry Coffin
A: 

The most correct way to actually test for file write permission is to attempt to write to the file. The reason for this is because different platforms expose write permissions in very different ways. Even worse, just because the operating system tells you that you can (or cannot) write to a file, it might actually be lying, for instance, on a unix system, the file modes might allow writing, but the file is on read only media, or conversely, the file might actually be a character device created by the kernel for the processes' own use, so even though its filemodes are set to all zeroes, the kernel allows that process (and only that process) to muck with it all it likes.

TokenMacGuy
+1  A: 

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.

larsmans
thanks, but i still do not under stand how i can know if i have permissions to write file to disk.
if i'll try and have no permissions i assume the the program will collapse and i want to prevent it by checking before. is there any command for checking writing permissions to disk (writing a new file) ?
Why should your program collapse? :S
Matteo Italia