最近项目中遇到一个遍历文件夹的问题,这个项目需要以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,如果验证没问题,会持续更新上传。
希望对你有帮助,谢谢!