• 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());
    }
    
  • 相关阅读:
    C#实体类对象修改日志记录
    C#中关于增强类功能的几种方式
    Elasticsearch入坑指南之RESTful API
    React入门实例
    .Net Core+Vue.js+ElementUI 实现前后端分离
    ElasticSearch入坑指南之概述及安装
    MySQL优化技巧
    RabbitMQ入门教程——路由(Routing)
    RabbitMQ入门教程——发布/订阅
    RabbitMQ入门教程——工作队列
  • 原文地址:https://www.cnblogs.com/narjaja/p/13203492.html
Copyright © 2020-2023  润新知