gpt4 book ai didi

c++ - 为路径的每个元素创建一个目录(如果它不存在)

转载 作者:太空狗 更新时间:2023-10-29 23:49:15 27 4
gpt4 key购买 nike

在 C++ 中,我想从路径 "path/that/consists/of/several/elements" 创建一个目录。我还想创建该目录的所有父目录,以防它们不存在。如何使用标准 C++ 做到这一点?

最佳答案

std::experimental::filesystem/std::filesystem (C++14/C++17) 提供 create_directories() .如果每个路径元素不存在,它都会创建一个目录。为此,它执行 create_directory()对于每个这样的元素。

#include <experimental/filesystem>
#include <iostream>

int main()
{
namespace fs = std::experimental::filesystem; // In C++17 use std::filesystem.

try {
fs::create_directories("path/with/directories/that/might/not/exist");
}
catch (std::exception& e) { // Not using fs::filesystem_error since std::bad_alloc can throw too.
std::cout << e.what() << std::endl;
}

return 0;
}

如果异常处理不合适,std::filesystem函数重载使用 std::error_code :

int main() {
namespace fs = std::experimental::filesystem; // In C++17 use std::filesystem.

std::error_code ec;
bool success = fs::create_directories("path/with/directories/that/might/not/exist", ec);

if (!success) {
std::cout << ec.message() << std::endl; // Fun fact: In case of success ec.message() returns "The operation completed successfully." using vc++.
}

return 0;
}

关于c++ - 为路径的每个元素创建一个目录(如果它不存在),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43940515/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com