Search code examples
cfile-permissionsfstat

Obtaining permissions for a file in C


I am looking for a way to check and make sure a file is readable, writeable, and exists, and if it is not I want to print a message stating so. I believe the information I am looking for can be found using fstat(), I just don't know the correct way to get it.

If open sets a specific errno if I try to open a unreadable, unwriteable, or non-existant file with O_RDRW, I think that would be the ideal solution.

Here is what I have tried:

//function to open the file
int f_open(const char *filename){
   int fid;
   if ((fid = open (filename, O_RDWR)) < -1){
      return -1;
   }

   struct stat fileStat;
   if (fstat(fid, &fileStat) < 0){
      return -1;
   }

   //check write permission
   if (!S_IWUSR(fileStat.st_mode)){
      printf("Not writeable\n");
      return -1;
   }
   //check read permissions
   if (!S_IRUSR(fileStat.st_mode)){
    printf("Not readable\n");
    return -1;
   }
   return fid;
}

I am receiving the following error when I try and compile:

tester.c: In function 'f_open':
tester.c:56:14: error: called object '128' is not a function
tester.c:60:14: error: called object '256' is not a function

Solution

  • You can use access for permission checking

    int rw = access(filename, R_OK | W_OK);
    if (rw == 0) {
        /* read/write granted */
    }