Cpp_创建目录
参考文章:https://blog.csdn.net/guotianqing/article/details/109823501
system调用
简单粗野,适用于Linux系统。
1 | int main(int argc, char **argv) |
此方式,直接使用系统命令执行Linux下mkdir命令创建目录,缺点是system系统调用时,要处理各种返回值情况。
mkdir函数
C++
中提供了用于创建目录的函数,原型如下:
1 | int mkdir(const char * path, mode_t mode); |
可能的错误如下:
- EACCES - 访问错误
- Search permission is denied on a component of the path prefix, or write permission is denied on the parent directory of the directory to be created.
- EEXIST - 已存在
- The named file exists.
- ELOOP - 链接错误
- A loop exists in symbolic links encountered during resolution of the path argument.
- EMLINK - 链接达到上限
- The link count of the parent directory would exceed
LINK_MAX
.
- The link count of the parent directory would exceed
- ENAMETOOLONG - 名字太长
- The length of the path argument exceeds
PATH_MAX
or a pathname component is longer thanNAME_MAX
.
- The length of the path argument exceeds
- ENOENT - 目录前缀有部分不存在
- A component of the path prefix specified by path does not name an existing directory or path is an empty string.
- ENOSPC - 没有足够空间
- The file system does not contain enough space to hold the contents of the new directory or to extend the parent directory of the new directory.
- ENOTDIR - 目录前缀有一部分不是目录
- A component of the path prefix is not a directory.
- EROFS - 文件系统只读
- The parent directory resides on a read-only file system.
目录的权限如下:
1 | User: S_IRUSR (read), S_IWUSR (write), S_IXUSR (execute) |
它们组合在一起,形成了如下快捷方式:
1 | Read + Write + Execute: S_IRWXU (User), S_IRWXG (Group), S_IRWXO (Others) |
使用mkdir函数,替换上面程序中的核心代码:
1 | ret = mkdir(path.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); |
boost库create_directory
1 |
|
编译时增加-lboost_system -lboost_filesystem
选项。
注意,以上函数只能用于创建单个目录,不能创建多级目录,否则会抛异常
1 | begin create signal_dir: ./c/d |
如果需要一次创建多级目录,需要调用create_directories
C++17库create_directory
原型如下:
1 | // 以所有权限创建单个目录,父目录必须存在,如果目录已经存在,不会报错 |
使用与boost类似,示例代码如下:
1 |
|