递归读取文件名
void listFiles(const std::string& path,std::vector<std::string>&vec) {
DIR* dir;
struct dirent* entry;
struct stat statbuf;
if ((dir = opendir(path.c_str())) == nullptr) {
std::cerr << "Error opening directory: " << path << std::endl;
return;
}
while ((entry = readdir(dir)) != nullptr) {
std::string entryName = entry->d_name;
std::string fullPath = path + "/" + entryName;
if (entryName != "." && entryName != "..") {
if (stat(fullPath.c_str(), &statbuf) == -1) {
std::cerr << "Error getting file stats for: " << fullPath << std::endl;
continue;
}
if (S_ISDIR(statbuf.st_mode)) {
// 递归调用以处理子目录
listFiles(fullPath,vec);
} else {
// 打印文件名
// std::cout << fullPath << std::endl;
vec.push_back(fullPath);
}
}
}
closedir(dir);
}
递归创建目录
#include <iostream>
 #include <string>
 #include <vector>
 #include <sys/stat.h>
 #include <sys/types.h>
 #include <unistd.h>
// 用于分割路径的函数
 std::vector<std::string> split(const std::string &path, const std::string &delimiter) {
     std::vector<std::string> tokens;
     size_t start = 0, end = 0;
     while ((end = path.find(delimiter, start)) != std::string::npos) {
         tokens.push_back(path.substr(start, end - start));
         start = end + delimiter.length();
     }
     tokens.push_back(path.substr(start));
     return tokens;
 }
// 递归创建目录的函数
 bool createDirectories(const std::string &path) {
     // 分割路径
     std::vector<std::string> pathParts = split(path, "/");
     //get current directory
     char buff[1024];
     if (getcwd(buff, sizeof(buff)) != nullptr) {
         std::cout << "Current path: " << buff << std::endl;
     } else {
         perror("getcwd() error");
     }
    std::string currentPath=std::string(buff);
     // 逐级创建目录
     for (size_t i = 0; i < pathParts.size(); ++i) {
         currentPath += "/" + pathParts[i];
         // 跳过空字符串
         if (currentPath == "/") {
             continue;
         }
         // 跳过非目录部分
         if (i < pathParts.size() - 1) {
             struct stat st;
             if (stat(currentPath.c_str(), &st) != 0) {
                 // 如果目录不存在,则创建它
                 if (mkdir(currentPath.c_str(), 0755) == -1) {
                     // 如果创建失败,并且不是因为目录已存在
                     if (errno != EEXIST) {
                         std::cerr << "Error creating directory: " << currentPath << std::endl;
                         return false;
                     }
                 }
             }
         }
     }
     return true;
 }
int test() {
     std::string dirPath = "path/to/your/directory";
     if (createDirectories(dirPath)) {
         std::cout << "Directories created successfully" << std::endl;
     } else {
         std::cerr << "Failed to create directories" << std::endl;
     }
     return 0;
 }