Windows及Linux系统中获取文件夹路径下的所有文件名

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;
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值