2

如何在 Kubuntu Linux 中使用 C++ 使用 sys/stat.h 中的 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 的文件模式位,但我不知道如何。见 sys/stat.h

4

2 回答 2

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;
于 2009-09-08T12:10:13.353 回答
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 个单独的权限位中的每一个都有单独的掩码。

于 2009-09-08T12:07:46.403 回答