c++ 文件夹读取文件

Linux

#include <dirent.h>

inline int getdir (std::string dir, std::vector<std::string> &files)
{
    DIR *dp;
    struct dirent *dirp;
    if((dp  = opendir(dir.c_str())) == NULL)
    {
        return -1;
    }

    while ((dirp = readdir(dp)) != NULL) {
        std::string name = std::string(dirp->d_name);

        if(name != "." && name != "..")
            files.push_back(name);
    }
    closedir(dp);


    std::sort(files.begin(), files.end());

    if(dir.at( dir.length() - 1 ) != '/') dir = dir+"/";
    for(unsigned int i=0;i<files.size();i++)
    {
        if(files[i].at(0) != '/')
            files[i] = dir + files[i];
    }

    return files.size();
}

Windows

#include <io.h>

using namespace std;
// vector<string> data;
//getFiles("D:/dataset", data, "*png");   找到所有.png文件
void getFiles(string path, vector<string>& files, string postfix)
{
    //文件句柄    
    intptr_t   hFile = 0;
    //文件信息    
    struct _finddata_t fileinfo;
    string p;
    if ((hFile = _findfirst(p.assign(path).append("\\*").c_str(), &fileinfo)) != -1)
    {
        do
        {
            if ((fileinfo.attrib & _A_SUBDIR))
            {
                if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
                    getFiles(p.assign(path).append("\\").append(fileinfo.name), files, postfix);
            }
            else
            {
                string str = fileinfo.name;
                if (str.substr(str.find_last_of('.')+1) == postfix.substr(1))
                    files.push_back(p.assign(path).append("\\").append(fileinfo.name));
            }
        } while (_findnext(hFile, &fileinfo) == 0);
        _findclose(hFile);
    }
    //sort(files.begin(), files.end());
}

原文链接: https://www.cnblogs.com/narjaja/p/13203492.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    c++ 文件夹读取文件

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/359890

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月2日 下午1:00
下一篇 2023年3月2日 下午1:00

相关推荐