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