将字符串转换为 mode_t

标签 c linux string permissions mode

<分区>

我有一个字符串“rwxrwxrwx”。

如何将其转换为类型 mode_t 以在 chmod 系统调用中使用?权限应为 -rwxrwxrwx。

最佳答案

您可以使用此代码。但是,可以使用 for 循环和一些模数来缩短它。

const char *perm = "rwxrwxrwx";
mode_t mode = 0;

if (perm[0] == 'r')
  mode |= 0400;
if (perm[1] == 'w')
  mode |= 0200;
if (perm[2] == 'x')
  mode |= 0100;
if (perm[3] == 'r')
  mode |= 0040;
if (perm[4] == 'w')
  mode |= 0020;
if (perm[5] == 'x')
  mode |= 0010;
if (perm[6] == 'r')
  mode |= 0004;
if (perm[7] == 'w')
  mode |= 0002;
if (perm[8] == 'x')
  mode |= 0001;

关于将字符串转换为 mode_t,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40321092/

相关文章:

ios - 使用字符进行字符串格式化会崩溃

string - 在 Scala 中比较字符串列表

c++ - linux 中的 sys/ioctl.h 问题

可以将字符串分配给 char 指针,而不会变成文字吗?

c - 在结构体内部使用结构体

c - AVX2 1x mm256i 32 位到 2x mm256i 64 位

javascript - 如何添加允许在 Umbraco 中添加新行的验证

c++ - 序列化和反序列化 uint64_t - 不同平台上的不同结果

linux - bash 命令截断

linux - 有没有办法禁用 Raspberry pi 3b+ 上的 USB 端口(不是以太网)?