views:

59

answers:

3

I see that ifstream::open() returns void and does not offer any way to see if the file did not open due to permissions. What is a good api to test whether read permission or alternatively write permissions are available on a file for the current process in C++?

+2  A: 

Try the POSIX access() function, in unistd.h

Paul Beckingham
+2  A: 

You can also use stat which returns a bunch of information, including mode, uid and gid:

   struct stat {
       dev_t     st_dev;     /* ID of device containing file */
       ino_t     st_ino;     /* inode number */
       mode_t    st_mode;    /* protection */
       nlink_t   st_nlink;   /* number of hard links */
       uid_t     st_uid;     /* user ID of owner */
       gid_t     st_gid;     /* group ID of owner */
       dev_t     st_rdev;    /* device ID (if special file) */
       off_t     st_size;    /* total size, in bytes */
       blksize_t st_blksize; /* blocksize for file system I/O */
       blkcnt_t  st_blocks;  /* number of 512B blocks allocated */
       time_t    st_atime;   /* time of last access */
       time_t    st_mtime;   /* time of last modification */
       time_t    st_ctime;   /* time of last status change */
   };

I am not aware of nice C++ wrappers for these lower-level functions.

Dirk Eddelbuettel
+1  A: 

If your using windows , you can use GetFileAttributesEx to check the attributes of the file. If its read-only, you might need to call SetFileAttributes to unset the read-only flag.

Andrew Keith