C++遍历路径下的所有文件

时间:2023-03-08 22:37:15

intptr_t类型用于记录文件夹句柄,注意该类型不是指针类型,而是int型的重定义。

_finddata_t结构体类型用于记录文件信息。

_finddata_t结构体定义如下

struct _finddata_t {

unsigned attrib;        // 存储文件属性
__time64_t time_create;     // 存储文件创建时间
__time64_t time_access;     // 存储文件最后一次被访问的时间
__time64_t time_write;      // 存储文件最后一次被修改的时间
_fsize_t size;          // 存储文件的大小
char name[260];        // 存储文件名称

};

_findfirst()函数

_findfirst()函数原型如下:

intptr_t _findfirst(

  const char *filespec,      // 目标文件

  struct _finddata_t *fileinfo    // 用于存储文件信息的_finddata_t结构体

);

函数如果成功,返回一个唯一的搜索句柄标识一个或一组和filespec说明匹配的文件,可以用于接下来的_findnext()和_findclose()函数。
否则_findfirst()返回-1。 _findnext()函数
_findnext()函数原型如下: int _findnext(
    intptr_t handle,            // 搜索句柄,通过_findfirst()函数获得
struct _finddata_t *fileinfo     // 用于存储文件信息的_finddata_t结构体
);
函数如果成功,返回0,否则返回-1。如果没有更多能够找到的文件了,也会导致失败。
_findclose()函数
原型如下:
int _findclose(
intptr_t handle    // 搜索句柄
);
该函数用于关闭搜索句柄 代码如下:
void CDlg::OnBnClickedOk()
{
// TODO: 在此添加控件通知处理程序代码
UpdateData(TRUE);
m_ListFile.ResetContent(); // 宽字节转多字节
char *pPathBuf = NULL;
int PathBufSize = WideCharToMultiByte(0, 0, m_szPath.GetBuffer(), m_szPath.GetLength(), pPathBuf, 0, NULL, NULL);
if (PathBufSize <= 0)
m_ListFile.AddString(_T("获取多字节缓冲区大小错误"));
pPathBuf = new char[PathBufSize + 1];
memset(pPathBuf, 0, PathBufSize + 1);
WideCharToMultiByte(0, 0, m_szPath.GetBuffer(), m_szPath.GetLength(), pPathBuf, PathBufSize + 1, 0, 0);
if (strlen(pPathBuf) <= 0)
m_ListFile.AddString(_T("宽字节转多字节错误")); queue<string> *pVect = new queue<string>;
if (GetPathFile(pPathBuf, pVect) == false)
m_ListFile.AddString(_T("遍历目录下的所有文件失败!"));
else{
while (!pVect->empty())
{
string szFileName = pVect->front();
LPWSTR pBuf = NULL;
int nLen = MultiByteToWideChar(0, 0, (char*)szFileName.c_str(), szFileName.length(), pBuf, 0);
if (nLen > 0)
{
pBuf = new TCHAR[nLen + 1];
memset(pBuf, 0, sizeof(TCHAR)* (nLen + 1));
MultiByteToWideChar(0, 0, (char*)szFileName.c_str(), szFileName.length(), pBuf, nLen);
m_ListFile.AddString(pBuf);
delete[] pBuf;
pBuf = NULL;
}
pVect->pop();
}
} delete[] pPathBuf;
pPathBuf = NULL;
UpdateData(FALSE);
} bool CDlg::GetPathFile(const char* pPath, queue<string> *pVect)
{
if (!pPath || !pPath)
return false;
char* szPath = new char[128];
memset(szPath, 0, 128);
_snprintf_s(szPath, 128, 128, "%s\\*.*", pPath);
intptr_t Handle;
_finddata_t FindData;
Handle = _findfirst(szPath, &FindData);
if (Handle == -1)
return false;
do
{
if (strcmp(FindData.name, ".") != 0 && strcmp(FindData.name, "..") != 0)
{
pVect->push(FindData.name);
if (strrchr(FindData.name, '.') == NULL)
{
string sz = pPath;
sz += "\\";
sz += FindData.name;
GetPathFile(sz.c_str(), pVect);
}
}
} while (_findnext(Handle, &FindData) == 0);
_findclose(Handle);
delete[] szPath;
szPath = NULL;
return true;
}