0

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
tshepang
  • 12,111
  • 21
  • 91
  • 136
Talen Kylon
  • 1,908
  • 7
  • 32
  • 60
  • Wouldn't it make more sense to check the permissions *before* you try to open the file? Especially since you don't close the file if the checks fail. – Some programmer dude Nov 21 '13 at 16:41
  • Closing is handled in a different function. My reason for calling open first is because I need the fid to call fstat(). – Talen Kylon Nov 21 '13 at 16:44
  • S_IWUSR is not a function! http://en.wikibooks.org/wiki/C_Programming/POSIX_Reference/sys/stat.h#Member_constants – Gowtham Nov 21 '13 at 16:44
  • Yes, but when you return `-1` the file *can't* be close by another function. – Some programmer dude Nov 21 '13 at 17:42
  • Although that won't matter with the code you have in the question, as `open` will fail if you don't have the correct permissions. So the access checks will only happen if the file exists and you can read and write it. – Some programmer dude Nov 21 '13 at 17:49

2 Answers2

4

The macros you are using are bit values, not functions.

//check write permission
if ((S_IWUSR & fileStat.st_mode) == 0){
    printf("Not writeable\n");
    return -1;
}

Example Here: http://codewiki.wikidot.com/c:system-calls:fstat

EDIT: The 'access' function indicated above is a better choice IWUSR doesnt tell you if YOU can write it, it tells you if the owner can.

Sanjaya R
  • 6,246
  • 2
  • 17
  • 19
3

You can use access for permission checking

int rw = access(filename, R_OK | W_OK);
if (rw == 0) {
    /* read/write granted */
}
Olaf Dietsche
  • 72,253
  • 8
  • 102
  • 198