c++读取文件夹下的文件路径(亲测超好用)

下面是主要代码(头文件记得包含):

#include 
#include 
#include 
#include 

using namespace std;

void getFiles(std::string path, std::vector<std::string>& files)
{
     
	intptr_t   hFile = 0;//intptr_t和uintptr_t的类型:typedef long int; typedef unsigned long int
	struct _finddata_t fileinfo;
	std::string p;
	if ((hFile = _findfirst(p.assign(path).append("/*").c_str(), &fileinfo)) != -1)//assign方法:先将原字符串清空,然后赋予新的值作替换。
	{
     
		do
		{
     
			if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
			{
     
				files.push_back(p.assign(path).append("/").append(fileinfo.name));
			}
		} while (_findnext(hFile, &fileinfo) == 0);
		_findclose(hFile);
	}
}

int main() {
     
	vector <string> files;
	//需要读取的文件夹路径,使用单右斜杠“/”
	string filePath = "C:/Users/WJY/Desktop/test_c++/test/datas";  
	//string filePath = "./datas"; //相对路径也可以
	getFiles(filePath, files);
	for (int i = 0; i < files.size(); i++) {
     
		cout << files[i] << endl;
	}

	return 0;
}

结果展示:
c++读取文件夹下的文件路径(亲测超好用)_第1张图片
c++读取文件夹下的文件路径(亲测超好用)_第2张图片

你可能感兴趣的:(c++,c++)