一、mkdir模块
#include <iostream>
#include <string>
#include <sys/stat.h> // 对于 UNIX 或 Linux 系统
if (mkdir(new_file_path.c_str(), 0755) == 0)
{
std::cout << "Directory created successfully." << std::endl;
}
else
{
std::cerr << "Failed to create directory." << std::endl;
throw std::runtime_error("Failed to create directory.");
}
已经有文件的,再创建不会报错,只不过返回值不是0
二、filesystem模块
1、安装环境
sudo apt-get update
sudo apt-get install libboost-all-dev
2、递归创建目录
#include <filesystem>
namespace fs = std::filesystem;
int main() {
fs::path dir = "/path/to/your/directory";
if (fs::create_directories(dir)) {
std::cout << "Successfully created directories!\n";
} else {
std::cout << "Failed to create directories or directories already exist!\n";
}
return 0;
}
编译
g++ test.cpp -lboost_filesystem -lboost_system