2009-09-08 47 views
2

如何使用C++在Kubuntu Linux中使用stat從sys/stat.h中獲取文件所有者的訪問權限?使用C++和stat獲取所有者的訪問權限

目前,我得到的文件類型是這樣的:

struct stat results; 

    stat(filename, &results); 

    cout << "File type: "; 
    if (S_ISDIR(results.st_mode)) 
    cout << "Directory"; 
    else if (S_ISREG(results.st_mode)) 
    cout << "File"; 
    else if (S_ISLNK(results.st_mode)) 
    cout << "Symbolic link"; 
    else cout << "File type not recognised"; 
    cout << endl; 

我知道我應該使用t_mode的文件模式位,但我不知道怎麼辦。 See sys/stat.h

回答

7
struct stat results; 

    stat(filename, &results); 

    cout << "Permissions: "; 
    if (results.st_mode & S_IRUSR) 
    cout << "Read permission "; 
    if (results.st_mode & S_IWUSR) 
    cout << "Write permission "; 
    if (results.st_mode & S_IXUSR) 
    cout << "Exec permission"; 
    cout << endl; 
1

所有者權限位由宏S_IRWXU<sys/stat.h>給出。該值將通過64(0100八進制)相乘,因此:

cout << "Owner mode: " << ((results.st_mode & S_IRWXU) >> 6) << endl; 

這將打印出0和7之間的值存在用於組(S_IRWXG)及其他(S_IRWXO)類似的掩模,用移3和0。對於12個單獨的權限位中的每一個,也有單獨的掩碼。

相關問題