【问题标题】:How to read a file permission and store it in a variable in C如何读取文件权限并将其存储在C中的变量中
【发布时间】:2013-08-27 12:12:16
【问题描述】:

在Linux平台(Ubuntu系统)。 如标题中所述。 我尝试获取像“0644”这样的数字并将其存储在变量中以备后用。

【问题讨论】:

标签: c linux file-permissions


【解决方案1】:

stat, fstat, lstat 系统调用可用于检索文件的权限。
stat 结构的st_mode 字段包含指定为系统调用参数的文件的权限。然后mode_t 类型的变量可以用作应用程序中的本地存储。

这是一个例子:

#include <sys/types.h>
#include <sys/stat.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>


#define FILE_NAME "test.c"

int main(int argc, char *argv[])
{
   struct stat sb;
   mode_t file_permision; 

   if (stat(FILE_NAME, &sb) == -1) {
        perror("stat");
        exit(EXIT_FAILURE);
    }

   file_permision = sb.st_mode; 
   printf(" File permission : %o (octal)\n",
            (unsigned int) file_permision); 
  return 0;
}

【讨论】:

  • 请注意,st_mode 也包含文件类型位(更不用说 SUID、SGID 和 SVTX 位)。
  • 是的,你是对的。事实上,这个程序的输出,例如100664,也显示了文件类型位。他应该使用适当的宏来处理 mode_t 类型的对象。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-11-05
  • 2015-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多