zoukankan      html  css  js  c++  java
  • 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());
    }
    
  • 相关阅读:
    BLE编程中关键步骤
    gradle相关配置内容解析
    Gradle版本变更的问题
    【问题】AndroidStudio导入项目一直卡在Building gradle project infod的最快速解决方案
    jdbc.properties各种数据库连接配置
    EL表达式语言总结
    Android sdk目录介绍
    chrome的常用快捷键和命令
    Unity Hub for Mac 破解
    MAC下安装配置Tomcat
  • 原文地址:https://www.cnblogs.com/narjaja/p/13203492.html
Copyright © 2011-2022 走看看