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());
    }
    
  • 相关阅读:
    输出流对象
    1.2最简单的c++程序
    c++的初步认识
    理想程序员
    从字符数组中删除字符
    打印杨辉三角
    旋转数组
    找出1000以内的所有完数
    计算兔子的总数
    101-200有多少个素数?
  • 原文地址:https://www.cnblogs.com/narjaja/p/13203492.html
Copyright © 2011-2022 走看看