Python os.makedirs(..., exist_ok=True) 的 C++ 等价物

在 C++17 中,你可以使用 std::filesystem,它提供了 std::filesystem::create_directories

类似于 Python 的 os.makedirs(..., exist_ok=True) 或 shell 命令 mkdir -p,这将递归创建目录。

mkdir_example.cpp
#include <iostream>
#include <filesystem>

namespace fs = std::filesystem;

int main() {
    std::string directoryPath = "output";

    try {
        // Create the directory
        fs::create_directories(directoryPath);
        std::cout << "Directory created successfully." << std::endl;
    } catch (const std::exception& ex) {
        std::cerr << "Error creating directory: " << ex.what() << std::endl;
    }

    return 0;
}

注意你通常需要告诉编译器使用 C++17 标准。例如,对于 GCC 使用 -std=c++17-std=gnu++17(如果你想使用 GNU 扩展)

build_mkdir.sh
g++ -o main main.cpp -std=c++17

如果你必须使用不支持 C++17 的旧编译器,你可能需要使用 std::experimental::filesystem,它基本上提供相同的 API,但在 std::experimental::filesystem 命名空间中:

mkdir_example_legacy.cpp
#include <iostream>
#include <experimental/filesystem>

namespace fs = std::experimental::filesystem;

int main() {
    std::string directoryPath = "output";

    try {
        // Create the directory
        fs::create_directories(directoryPath);
        std::cout << "Directory created successfully." << std::endl;
    } catch (const std::exception& ex) {
        std::cerr << "Error creating directory: " << ex.what() << std::endl;
    }

    return 0;
}

Check out similar posts by category: C/C++