【问题标题】:How to change permissions of a file in Linux with C++ [closed]如何使用 C++ 在 Linux 中更改文件的权限 [关闭]
【发布时间】:2016-05-15 02:35:45
【问题描述】:

我想在 Linux 中使用 C++ 更改文件的权限。用户必须使用以下语法输入权限:“请输入权限:rwx-w-r--”在终端中。

感谢您的帮助。

【问题讨论】:

标签: c++ linux permissions system-calls


【解决方案1】:
#include <sys/types.h>
#include <sys/stat.h>

int main() { 
  chmod("./myfile", S_IRWXU); // enables owner to rwx file
}

更多详情请见man 2 chmod

如果问题是如何解析形式为“rwx-w-r--”的 9 个字符的字符串,请意识到权限以 int 形式编码为位。如果有一点打开,则该权限处于打开状态。以下代码将以明显的方式将您的字符串转换为位...不进行验证等。这是一个概念验证。

#include <cstdio>
#include <sys/types.h>
#include <sys/stat.h>

int parse(char* perms) {
  int bits = 0;
  for(int i=0; i<9; i++){
    if (perms[i] != '-') {
      bits |= 1<<(8-i);
    }
  }
  return bits;
}
int main() { 
  char perms[]="rwx-w-r--";
  int exmp = S_IRWXU | S_IWGRP | S_IROTH;
  printf("%d %d\n", parse(perms), exmp);
  // outputs 468 468
}

【讨论】:

    猜你喜欢
    • 2013-07-13
    • 2013-05-27
    • 1970-01-01
    • 2018-08-03
    • 1970-01-01
    • 2014-12-16
    • 2021-09-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多