2009-12-11 50 views
2

我看到ifstream :: open()返回void,并且不提供任何方法来查看文件是否由于权限而未打开。什么是一个好的API来测试读取权限还是写入权限在C++中的当前进程的文件上可用?什么是测试文件是否具有所需权限的好方法?

+1

I/O是操作系统特定的,也许如果你能告诉我们你的操作系统,它可能会给出更具体的答案。 – 2009-12-11 02:30:17

+0

可能的重复:http://stackoverflow.com/questions/1138508/in-c-on-unix-how-can-a-process-tell-what-permissions-it-has-to-a-file-without- op – 2009-12-11 17:58:06

+0

这是针对Linux的。 – WilliamKF 2009-12-12 00:30:33

回答

2

尝试POSIX访问()函数,在unistd.h中

2

您还可以使用stat返回一大堆信息,包括模式,UID和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 */ 
    }; 

我不知道用于这些低级函数的很好的C++包装器。

1

如果您在使用Windows,您可以使用GetFileAttributesEx来检查文件的属性。如果它是只读的,则可能需要调用SetFileAttributes以取消设置只读标志。

相关问题