<分区>
我有一个字符串“rwxrwxrwx”。
如何将其转换为类型 mode_t 以在 chmod 系统调用中使用?权限应为 -rwxrwxrwx。
标签 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/