获取window系统一个目录下所有的文件名(除目录)

最近项目中优化一些代码等,给予项目中的代码进行重构,印象比较深的是对于文件操作来说,这些基本的小功能,在项目中经常遇到,如:最简单的获取window系统下某个目录下的所有文件名,为了完成这个功能,在window系统下需要添加头文件:#include <windows.h>,实现的代码如下:

#include<iostream>
#include<string>
#include<vector>
#include <windows.h>

//函数的功能实现:
void GetAllFilesFromDirectory(const std::string&dir, std::vector<std::string>& paths)
{

#ifdef _WIN32
	WIN32_FIND_DATA data;
	HANDLE hf = FindFirstFile((dir + "/*").c_str(), &data);
	if (hf == INVALID_HANDLE_VALUE)
	{
		printf("Cannot open directory");
		return;
	}
	do
	{
		if (!std::strcmp(data.cFileName, "."))
			continue;
		if (!std::strcmp(data.cFileName, ".."))
			continue;
		bool is_dir = (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
		if (!is_dir)
		{
			paths.emplace_back(data.cFileName);
		}
		else
		{
			GetAllFilesFromDirectory(dir + "/"+ data.cFileName, paths);
		}
	} while (FindNextFile(hf, &data) != 0);
	
	FindClose(hf);
#endif
}

测试结果:
在这里插入图片描述
上述的功能是获取目录下所有的文件名字,包括它的子目录下的文件。

如果只想获取当前的目录下的文件,不获取子目录下的文件,则可以用如下代码(去掉递归即可):

void GetCurrentFilesFromDirectory(const std::string&dir, std::vector<std::string>& paths)
{

#ifdef _WIN32
	WIN32_FIND_DATA data;
	HANDLE hf = FindFirstFile((dir + "/*").c_str(), &data);
	if (hf == INVALID_HANDLE_VALUE)
	{
		printf("Cannot open directory");
		return;
	}
	do
	{
		if (!std::strcmp(data.cFileName, "."))
			continue;
		if (!std::strcmp(data.cFileName, ".."))
			continue;
		bool is_dir = (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
		if (!is_dir)
		{
			paths.emplace_back(data.cFileName);
		}
	} while (FindNextFile(hf, &data) != 0);
	FindClose(hf);
}

测试的最后的代码如下:

int main(int argc, char** argv)
{
	std::string dir = "D:/vc_projects/Project_test/test";
	std::vector<std::string> paths;
	GetAllFilesFromDirectory(dir, paths);
	for (int i = 0; i < paths.size(); ++i)
	{
		std::cout << paths[i] << std::endl;
	}
	system("pause");
	return 0;
}

希望能帮助到大家。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值