bool CreateDirs(const std::string& dirName)
{
uint32_t dirPathLen = dirName.length();
if (dirPathLen > 256)
{
return -1;
}
char tmpDirPath[256] = { 0 };
for (uint32_t i = 0; i < dirPathLen; ++i)
{
tmpDirPath[i] = dirName[i];
if (tmpDirPath[i] == '\\' || tmpDirPath[i] == '/')
{
if (access(tmpDirPath, F_OK) != 0)
{
int32_t ret = mkdir(tmpDirPath, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
if (ret != 0)
{
return ret;
}
}
}
}
return 0;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
chattptgpt
在C++中,可以使用boost::filesystem库来创建多级目录。以下是一个使用 boost::filesystem 库的简单示例:
#include
namespace fs = boost::filesystem;
std::string createDirectory(const std::string& path) {
try {
fs::path directory(path);
if (!fs::exists(directory)) {
if (fs::create_directories(directory)) {
return "Directory created successfully.";
} else {
return "Failed to create directory.";
}
} else {
return "Directory already exists.";
}
} catch(const fs::filesystem_error& e) {
return "An error occurred: " + std::string(e.what());
}
}
int main() {
std::string path = "/home/syy/data/img";
std::string result = createDirectory(path);
std::cout << result << std::endl;
return 0;
}
在上面的代码中,boost::filesystem库的path类用于表示目录路径。我们使用fs::path来创建了一个表示目标目录路径的directory对象。之后,我们使用fs::exists()函数来检查目录是否已经存在。如果目录不存在,我们使用fs::create_directories()函数来创建目录。如果创建成功,函数返回true,否则返回false。
注意,需要使用boost::filesystem库的头文件<boost/filesystem.hpp>,并添加链接参数-lboost_system -lboost_filesystem来编译以上代码。
希望这个简单的C++示例能够帮助您创建多级目录。
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
文心一言
```cpp
在C++中,创建一个多级目录的有效方法是使用标准库中的 <filesystem> 头文件,其中包含了 std::filesystem::create_directories() 函数。这个函数可以递归地创建多级目录,如果目录已存在,那么就不会再创建。
下面是一个简单的示例代码:
cpp
#include
#include
namespace fs = std::filesystem;
int main() {
fs::path path("/home/syy/data/img");
if (fs::create_directories(path)) {
std::cout << "目录创建成功!" << std::endl;
} else {
std::cout << "目录创建失败!" << std::endl;
}
return 0;
}
这个示例代码使用了 <filesystem> 头文件中的 std::filesystem::create_directories() 函数来创建一个多级目录。fs::path 对象表示要创建的目录路径,然后调用 fs::create_directories() 函数来创建目录。如果目录创建成功,输出 "目录创建成功!",否则输出 "目录创建失败!"。
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25