mkdir

本文介绍如何使用mkdir函数从sys/stat.h POSIX头文件中创建目录,包括如何设置mode_t参数来定义新目录的权限。提供了不同权限组合的具体示例。

1,mkdir 

Problem: You want to use the mkdir() function from the sys/stat.h POSIX header, but you don’t know what the mode_t argument should look like.

Solution:

For a detailed reference, see the Opengroup page on mkdir

The first argument should be obvious - just enter the path name of the directory you intend to create. If you use a std::string (in C++); use it’s c_str() member function to get a C string.

The second argument defines the permissions the newly created directory shall have. This How-to assumes you’re already familiar with Unix file permissions. If you are not, please read the corresponding Wikipedia Page.

First, decide which rights the directory shall have. This boils down to these 9 questions:

  • Shall the owner be able to read/write/execute?
  • Shall the group be able to read/write/execute?
  • Shall everyone else (= others) be able to read/write/execute? The second argument has the type mode_t, but this is basically just an alias for any type of integer.

sys/stat.h provides you with several integers you can bytewise-OR (|) together to create your mode_t:

  • User: S_IRUSR (read), S_IWUSR (write), S_IXUSR (execute)
  • Group: S_IRGRP (read), S_IWGRP (write), S_IXGRP (execute)
  • Others: S_IROTH (read), S_IWOTH (write), S_IXOTH (execute)

Additionally, some shortcuts are provided (basically a bitwise-OR combination of the above

  • Read + Write + Execute: S_IRWXU (User), S_IRWXG (Group), S_IRWXO (Others)
  • DEFFILEMODE: Equivalent of 0666 = rw-rw-rw-
  • ACCESSPERMS: Equivalent of 0777 = rwxrwxrwx Therefore, to give only the user rwx (read+write+execute) rights whereas group members and others may not do anything, you can use any of the following mkdir() calls equivalently:
mkdir("mydir", S_IRUSR | S_IWUSR | S_IXUSR); mkdir("mydir", S_IRWXU); 

In order to give anyone any rights (mode 0777 = rwxrwxrwx), you can use any of the following calls equivalently:

mkdir("mydir", S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IWGRP | S_IXGRP | S_IROTH | S_IWOTH | S_IXOTH); mkdir("mydir", S_IRWXU | S_IRWXG | S_IRWXO); mkdir("mydir", ACCESSPERMS);

转载于:https://www.cnblogs.com/Dennis-mi/p/5757529.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值