c++——读取文件夹下的所有文件名

目录

1.读取某一文件夹下的文件名(非迭代式)

2.读取某一文件夹下的所有文件名(迭代式)

Tips:


主要是通过_findfirst和_findnext来实现。

1.读取某一文件夹下的文件名(非迭代式)

#include <stdio.h>
#include <io.h>
#include <stdlib.h>
#include <vector>
#include <iostream>
#include<fstream>  //ifstream
#include<string>     //包含getline()
#include<cmath>
using namespace std;

int main(void)
{
	intptr_t Handle;
	struct _finddata_t FileInfo;
	string p;
	string path = "leapData\\TipsPos";
	if ((Handle = _findfirst(p.assign(path).append("\\*").c_str(), &FileInfo)) == -1)
		printf("没有找到匹配的项目\n");
	else
	{
		printf("%s\n", FileInfo.name);
		while (_findnext(Handle, &FileInfo) == 0)
			printf("%s\n", FileInfo.name);
		_findclose(Handle);
	}
	return 0;
}

2.读取某一文件夹下的所有文件名(迭代式)

#include <stdio.h>
#include <io.h>
#include <stdlib.h>
#include <vector>
#include <iostream>
#include<fstream>  //ifstream
#include<string>     //包含getline()
#include<cmath>
using namespace std;

void getFiles(string path, vector<string>& files)
{
	//文件句柄
	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);
			}
			else
			{
				files.push_back(p.assign(path).append("\\").append(fileinfo.name));
			}
		} while (_findnext(hFile, &fileinfo) == 0);
		_findclose(hFile);
	}
}

int main(int argc, char** argv)
{
	string filePath = "leapData\\TipsPos\\";
	vector<string> files;

	////获取该路径下的所有文件
	getFiles(filePath, files);

	char str[30];
	int size = files.size();
	int nullSize = 0;
	for (int i = 0; i < size; i++)
	{
		cout << files[i].c_str() << endl;

/*
		string s;

		ifstream inf;
		inf.open(files[i].c_str());
		while (getline(inf, s)){
			if (s == "null"){
				cout << files[i].c_str() << ":NULL" << endl;
				nullSize++;
			}
		}
*/
	}
//	cout << nullSize << ": " << size << endl;
//	cout << (float)nullSize / size << endl;

	return 0;
}

Tips:

1.输出的结果是包含"."和".."的如果不需要,可以通过判断去除

2.handle的类型也可以是long,但是在64位下不可用;而intptr_t既可以在32位下使用,也可以在64位下使用。

发布了44 篇原创文章 · 获赞 14 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/hehehetanchaow/article/details/89633025
今日推荐