从C

时间:2018-04-08 20:28:03

标签: c bitmask octal

我试图使用函数stat()获取文件或目录的文件权限。我可以得到正确的信息,例如; st_nlinks用于硬链接的数量,st_mode给出文件的模式,这是我正在寻找的。但是st_mode中的值存储是一个八进制数。我现在如何仅提取所有者权限。

例如,st_mode可能存储42755,这意味着所有者已经读取了写入和执行权限,但我不知道如何从数字中提取7。如果这令人困惑,我的下面代码可能会澄清事情。

CODE:

DIR *dirp;
struct dirent *dp;
struct stat buf;

dirp = opendir(".");
while ((dp = readdir(dirp)) != NULL){
   stat(dp->d_name, &buf);

   //now here I have the octal number for the file permissions
   //If I put a print statement here like so:
   printf(">> %o %s\n", buf.st_mode, dp->d_name);
}

所以有些人可能会发现我正在尝试在Unix系统上执行ls -l所做的事情。因此,不是打印模式的八进制数,而是将其转换为:

drwxr-xr-x for the value stored in st_mode: 42755

我的教授建议使用蒙版并对其执行按位操作。我理解他的意思,但我尝试了类似的东西:

mode_t owner = 0000100 & st_mode;

但是当我打印出所有者时,我得到了100的值。

printf(">> owner permission: %o\n", owner);

输出:

owner permission: 100

所以我很困惑如何做到这一点。有谁知道如何解决这个问题?

顺便提一下,如果有人想知道我使用mode_t作为所有者的类型,因为根据stat(man 2 stat)的手册页,stat结构的成员变量st_mode是mode_t类型。我认为这就像一个长int或者什么。

3 个答案:

答案 0 :(得分:1)

您应该考虑使用已定义的宏而不是尝试解析"权限手动。我们假设您希望获得文件所有者用户的写入权限,可以像这样检查:

int wpo = buff.st_mode & S_IWUSR;
if (wpo) {
  printf("Ower has write permission");
} else {
  printf("Ower doesn't have write permission");
}

您会在文档中找到更多有用的宏:http://pubs.opengroup.org/onlinepubs/009695399/basedefs/sys/stat.h.html

答案 1 :(得分:1)

面具必须是0700: 111 000 000 获得所有者权利rwx

答案 2 :(得分:0)

使用sys / stat.h中定义的宏来解析模式位。

参考: http://www.johnloomis.org/ece537/notes/Files/Examples/ls2.html 函数mode_to_letters()用于实现细节。