C++ equivalent of Python's os.makedirs(..., exist_ok=True)
In C++17, you can use std::filesystem
which provides std::filesystem::create_directories
.
Similar to Python’s os.makedirs(..., exist_ok=True)
or the shell command mkdir -p
, this will recursively create directories.
#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;
}
Note that you typically need to tell your compiler to use the C++17 standard. For example, for GCC use -std=c++17
or -std=gnu++17
in case you want to use GNU extensions
g++ -o main main.cpp -std=c++17
If you have to use an older compiler not supporting C++17 , you might need to use std::experimental::filesystem
which basically provides the same API but in the std::experimental::filesystem
namespace:
#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;
}