2009-12-11 49 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以取消設置只讀標誌。

相關問題