问题描述
我试图编写一个简单的C程序来创建目录(一个mkdir克隆).这是我到目前为止的内容:
I am trying to write a simple C program that creates directories (a mkdir clone.). This is what I have so far:
#include <stdlib.h>
#include <sys/stat.h> // mkdir
#include <stdio.h> // perror
mode_t getumask()
{
mode_t mask = umask(0);
umask (mask);
return mask;
}
int main(int argc, const char *argv[])
{
mode_t mask = getumask();
printf("%i",mask);
if (mkdir("trial",mask) == -1) {
perror(argv[0]);
exit(EXIT_FAILURE);
}
return 0;
}
此代码使用d---------
创建目录,但我希望它像mkdir一样使用drwxr-xr-x
创建目录?我在这里做什么错了?
This code creates directory with d---------
but I want it to create it with drwxr-xr-x
like mkdir do? What am I doing wrong here?
这是适合我的解决方案:
This is the working solution for me:
int main(int argc, const char *argv[])
{
if (mkdir("trial",0777) == -1) {
perror(argv[0]);
exit(EXIT_FAILURE);
}
return 0;
}
根据umask设置权限的权限会自动处理.因此,我只需要调用具有完全权限的mkdir即可,并且根据当前的umask将其切碎.
Setting right permissions according to umask is automatically handled. So I only needed to call mkdir with full permissions, and that gets chopped according to current umask.
推荐答案
正如Eric所说,umask是您获得的实际权限模式的补充.因此,您应该将0777-mask
传递给mkdir()
,而不是将遮罩本身传递给mkdir()
.
As Eric says, umask is the complement of the actual permission mode you get. So instead of passing mask itself to mkdir()
, you should pass 0777-mask
to mkdir()
.
这篇关于如何在Posix上使用C创建具有正确权限的目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!