#include <iostream>
#include <sys/stat.h>
#include <sys/types.h>
#include <cstring> // For strerror
#include <string>
#include <errno.h>
// 函数声明
bool create_directory_recursive(const std::string& path);
bool create_directory_recursive(const std::string& path) {
// 临时变量,用于逐级构建路径
std::string temp_path;
size_t pos = 0;
// 处理路径中的每一层
while ((pos = path.find('/', pos)) != std::string::npos) {
temp_path = path.substr(0, pos++);
if (temp_path.empty()) continue; // 忽略根路径 "/"
// 检查目录是否已经存在
if (mkdir(temp_path.c_str(), 0755) && errno != EEXIST) {
std::cerr << "Error creating directory: " << strerror(errno) << std::endl;
return false;
}
}
// 创建最后一级目录
if (mkdir(path.c_str(), 0755) && errno != EEXIST) {
std::cerr << "Error creating directory: " << strerror(errno) << std::endl;
return false;
}
return true;
}
int main() {
std::string path = "/home/mazu/test/dir1/dir2";
// 递归创建目录
if (create_directory_recursive(path)) {
std::cout << "Directories created successfully!" << std::endl;
} else {
std::cout << "Failed to create directories." << std::endl;
}
return 0;
}
12-29