7

I'm writing an simple file server using sockets for an assignment. Before I start accepting connections I need to check that the server can write to the requested directory it serves from.

One simple way of doing this would simply be to try create a file and then delete it straight afterwards and error if that failed. But what if the file already exists? My program crashes or gets closed in-between? Along with the fact it seems a bit messy and isn't elegant.

Strictly speaking the code only needs to work for an Ubuntu system the markers test it on. So I could do a stat() command, get the current uid and gid and check the permissions manually against the file status. But I'd rather do this in a portable fashion and this is laborous..

Is there a simple C standard way of doing this?

  • 1
    You know about access() ? – Charlie Burns Oct 25 '13 at 20:04
  • No i did not. It looks like a access() call with the path of the directory and the how argument of W_OK may work. I can then check to see if it returns 0. I'll test it out now. – Callum Oct 25 '13 at 20:08
7

You could use access from <uninstd.h>. I don't know if it's part of the standard, but it is more convenient than stat, I would say.

#include <errno.h>
#include <unistd.h>
#include <iostream>

int main(int argc, char** argv)
{
    int result = access("/root/", W_OK);
    if (result == 0)
    {
        std::cout << "Can W_OK" << std::endl;
    }
    else
    {
        std::cout << "Can't W_OK: " << result << std::endl;
    }
}
|improve this answer|||||
  • Thanks. Posted my C version below also. – Callum Oct 25 '13 at 20:14
  • access checks with real UID instead of effective UID. You need to use faccessat with AT_EACCESS flag to check the accessibility with effective user and group IDs. – Zangetsu Jun 23 '16 at 2:17
6

Yes it works, cheers.

#include <unistd.h>
#include <stdbool.h>

bool is_folder_writable(char* str) {
    if(access(str, W_OK) == 0) {
        return true;
    } else {
        return false;   
    }
}
|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.