Windows及Linux系统中创建目标路径文件夹,以及获取目标文件夹路径下的所有文件名

本文介绍了在C++中,如何分别在Linux和Windows系统下使用不同的方法遍历文件夹并获取后缀名为.bin的文件名。hasEnding函数用于检查字符串是否以特定后缀结束,getFolderFile函数是核心部分,展示了两种操作系统下的文件搜索和处理策略。
摘要由CSDN通过智能技术生成

1. 创建目标路径文件夹

int CreatFolders(const std::string& folder_path) {
    int len = folder_path.length();
    char tmpDirPath[256] = { 0 };
    for (int i = 0; i < len; i++) {
        tmpDirPath[i] = folder_path[i];
        if (tmpDirPath[i] == '\\' || tmpDirPath[i] == '/') {
#ifdef _WIN32
            if (_access(tmpDirPath, 0) != 0) {
                int ret = _mkdir(tmpDirPath);
                if (ret == -1) return ret;
            }
#else
            if (access(tmpDirPath, 0) != 0)
            {
                std::cout << tmpDirPath << "tmpDirPath" << std::endl;
                if (mkdir(tmpDirPath, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) == -1)
                {
                    perror(folder_path.c_str());
                    return -1;
        }
                std::cout << "Directory created successfully ! " << std::endl;
    }
#endif
        }
    }
    return 0;
}

2. 批量获取目标路径下指定格式的文件名

Linux系统:

#include <string.h>
#include <iostream>
#include <sstream>
#include <fstream>
#include <dirent.h>

bool hasEnding(std::string const &fullString, std::string const &ending)
{
    if (fullString.length() >= ending.length()) {
        return (0 == fullString.compare (fullString.length() - ending.length(), ending.length(), ending));
    } else {
        return false;
    }
}

int getFolderFile(const char *path, std::vector<std::string>& files, const char *suffix = ".bin")
{
    DIR *dir;
    struct dirent *ent;
    if ((dir = opendir(path)) != NULL) {
        while ((ent = readdir (dir)) != NULL) {
            std::string file = ent->d_name;
            if(hasEnding(file, suffix)){
                files.push_back(file.substr(0, file.length()-4));
            }
        }
        closedir(dir);
    } else {
        printf("No such folder: %s.", path);
        exit(EXIT_FAILURE);
    }
    return EXIT_SUCCESS;
}

Windows系统:

#undef UNICODE
#include <windows.h>

#include <string.h>
#include <iostream>
#include <sstream>
#include <fstream>
#include <thread>
#include <filesystem>

int getFolderFile(const char* path, std::vector<std::string>& files, const char* suffix = ".bin")
{
    WIN32_FIND_DATA findData;
    char filePathName[256];
    strcpy(filePathName, path);
    strcat(filePathName, "/*");
    strcat(filePathName, suffix);

    //HANDLE hFind = FindFirstFile((path +"*" + suffix).cstr(), &findData);
    HANDLE hFind = FindFirstFile(filePathName, &findData);

    if (hFind == INVALID_HANDLE_VALUE)
    {
        printf("No such folder or no such files: %s\n", path);
        return EXIT_FAILURE;
    }
    do
    {
        std::string filename = findData.cFileName;

        size_t lasDotPos = filename.find_last_of(".");//查找最后一个点号位
        if (lasDotPos != std::string::npos)
            filename.erase(lasDotPos); //删除从最后一个点号到结尾的部分

        files.push_back(filename);
    } while (FindNextFile(hFind, &findData) != 0);
    FindClose(hFind);
    return EXIT_SUCCESS;
}

二合一版:


bool ends_with(const std::string& str, const std::string& suffix)
{
   return str.size()>=suffix.size() &&
          str.compare(str.size() - suffix.size(), suffix.size(), suffix) ==0;
}


int GetAllFilesName(const std::string& dir_path, const std::string& suffix,
                    std::vector<std::string>* files_name) {
#ifdef _WIN32
    int ret = 0;
    intptr_t dirHandle;
    struct _finddata_t fileinfo;
    dirHandle = _findfirst((dir_path + suffix).c_str(), &fileinfo);
    do {
        if (dirHandle == -1) {
            ret = -1;
            break;
        }
        files_name->push_back(fileinfo.name);
    } while (!_findnext(dirHandle, &fileinfo));
    _findclose(dirHandle);
    if (files_name->size() == 0) {
        ret = -1;
    }
    return ret;
#else
    int ret = 0;
    DIR* dp;          //目录流
    struct dirent* entry;     //目录项信息
    struct stat statbuf;
    //打开目录, 判断目录是否存在
    if ((dp = opendir(dir_path.c_str())) == 0) {
        fprintf(stderr, "open dir %s failed\n", dir_path.c_str());
        return -1;
    }
    //读取目录信息
    while ((entry = readdir(dp)) != 0) {
        //忽略 . ..目录
        if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, "..")) {
            continue;
        }
        std::string filename = entry->d_name;
        // if (MyUtils::isStringMatched(filename.c_str(), suffix.c_str()))
        if(ends_with(filename,suffix))
            files_name->push_back(filename);
    }
    closedir(dp);
    if (files_name->size() == 0) {
        ret = -1;
    }
    return ret;
#endif
}//end GetAllFilesName

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值