C++遍历指定文件夹下的所有文件(包括子目录下的文件)

文章提供了一个使用C语言编写的DLL函数,用于遍历指定路径下的文件夹,同时处理Unicode字符集的转换问题。函数利用WIN32_FIND_DATA结构和FindFirstFile/FindNextFileAPI,递归查找目录中的文件。代码还包括一个简单的测试示例,展示如何在控制台应用此DLL。
摘要由CSDN通过智能技术生成

最近项目中遇到一个遍历文件夹的问题,这个项目需要以dll的形式给出,所以常规的QT方式的那些库基本上不怎么用,以C的方式写了一个,期间遇到各种字符转换的问题,这里dll的字符集采用的是unicode字符集,亲测通过,将源码分享出来。

void fileOperator::find(char * lpPath, std::vector<std::string> &fileList)
{
	char szFind[MAX_PATH];
	WIN32_FIND_DATA FindFileData;
	strcpy_s(szFind, strlen(lpPath) + 1, lpPath);
	strcat_s(szFind, "\\*.*");
	WCHAR w[256];
	memset(w, 0, sizeof(w));
	MultiByteToWideChar(CP_ACP, 0, szFind, strlen(szFind) + 1, w, sizeof(w) / sizeof(w[0]));
	HANDLE hFind = FindFirstFile((const WCHAR*)w, &FindFileData);
	if (INVALID_HANDLE_VALUE == hFind)
	{
		return;
	}

	while (true)
	{
		if (FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
		{
			if (FindFileData.cFileName[0] != '.')
			{
				char szFile[MAX_PATH];
				strcpy_s(szFile, lpPath);
				strcat_s(szFile, "\\");
				strcat_s(szFile, ConvertLPWSTRToLPSTR(FindFileData.cFileName));
				find(szFile, fileList);
			}
		}
		else
		{
			fileList.push_back(ConvertLPWSTRToLPSTR(FindFileData.cFileName));
		}
		if (!FindNextFile(hFind, &FindFileData))
		{
			break;
		}
	}
	FindClose(hFind);
}

char* fileOperator::ConvertLPWSTRToLPSTR(LPWSTR lpwszStrIn)
{
	LPSTR pszOut = NULL;
	try
	{
		if (lpwszStrIn != NULL)
		{
			int nInputStrLen = wcslen(lpwszStrIn);

			// Double NULL Termination  
			int nOutputStrLen = WideCharToMultiByte(CP_ACP, 0, lpwszStrIn, nInputStrLen, NULL, 0, 0, 0) + 2;
			pszOut = new char[nOutputStrLen];

			if (pszOut)
			{
				memset(pszOut, 0x00, nOutputStrLen);
				WideCharToMultiByte(CP_ACP, 0, lpwszStrIn, nInputStrLen, pszOut, nOutputStrLen, 0, 0);
			}
		}
	}
	catch (std::exception e)
	{
	}

	return pszOut;
}

测试demo如下,新建一个控制台工程

#include <stdio.h>
#include <iostream>
#include <vector>
#include <Windows.h>
#include <fstream>
#include <iterator>
#include <string>
#include <atlstr.h>

int main()
{
	std::vector<std::string> fileList;
	char p[6] = "D:\\1";
	find(p, fileList);
	for (int i = 0;i < fileList.size();i++)
	{
		std::cout << fileList[i] << std::endl;
	}
	std::cout << "文件数目:" << fileList.size() << std::endl;
	getchar();
	return 0;
}

其中,#include <atlstr.h>这个头文件是用来做宽字节字符转换使用的,必须包含,以上是原代码,大家可以下载新建工程使用,后续会写一个断点续传的dll,如果验证没问题,会持续更新上传。

希望对你有帮助,谢谢!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值