如何将文件权限打印为字符串? [英] How do I print file permissions as a string?
问题描述
我有一个 mode_t perms 变量,它存储从另一个函数返回的文件的权限.我需要将文件权限打印为
I have a mode_t perms variable which stores the permission for a file returned from another function. I need to print the file permissions as a tring, of the form
rw-r--r-- (0644)
但我得到的是
r--r--r-- (100644)
我怎样才能获得正确的权限?我试过谷歌搜索,但不明白我做错了什么.这是我的代码:
How can I get the right permissions? I've tried googling and don't understand what I'm doing wrong. Here's my code:
void print_perms(mode_t perms)
{
printf( (perms & S_IRUSR) ? "r" : "-");
printf( (perms & S_IWUSR) ? "w" : "-");
printf( (perms & S_IXUSR) ? "x" : "-");
printf( (perms & S_IRGRP) ? "r" : "-");
printf( (perms & S_IWGRP) ? "w" : "-");
printf( (perms & S_IXGRP) ? "x" : "-");
printf( (perms & S_IROTH) ? "r" : "-");
printf( (perms & S_IWOTH) ? "w" : "-");
printf( (perms & S_IXOTH) ? "x" : "-");
}
//later
print_perms(permissions);
printf(" (%d)\n", permissions);
推荐答案
首先,UNIX 的文件权限通常以八进制表示,对应的格式字符串是%o",而不是%d".rw-r--r--实际上是0644
,但是在C语言中0644 == 420
,例如(后者是十进制的).
First, UNIX file permissions are conventionally expressed in octal, corresponding format string is "%o", not "%d". rw-r--r-- is really 0644
, but in C language 0644 == 420
, for example (the latter is in decimal).
其次,使用的位比代码中指定的 9 多.你实际上应该说类似
Second, there are more bits used than 9 specified in the code. You actually should say something like
printf(" (%3o)", perms&0777);
这篇关于如何将文件权限打印为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!