如何创建与使用C POSIX上正确的任何权限目录 [英] How to create directory with right permissons using C on Posix
问题描述
我想编写一个创建目录的一个简单的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;
}
这code创建目录与 D ---------
,但我想它与 drwxr-创建XR-X
样的mkdir呢?我在做什么错在这里?
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.
推荐答案
随着埃里克说,umask是实际的许可模式,你得到的补充。因此,而不是通过面膜本身的mkdir()
,你应该通过 0777-面具
到 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()
.
这篇关于如何创建与使用C POSIX上正确的任何权限目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!