Windows程序设计之使用FindFirstFile和FindNextFile遍历文件夹

一、FindFirstFile和FindNextFile函数

HANDLE FindFirstFile(
  LPCTSTR lpFileName,               // file name
  LPWIN32_FIND_DATA lpFindFileData  // data buffer
);

BOOL FindNextFile(
  HANDLE hFindFile,                // search handle 
  LPWIN32_FIND_DATA lpFindFileData // data buffer
);

typedef struct _WIN32_FIND_DATA {
  DWORD    dwFileAttributes; 
  FILETIME ftCreationTime; 
  FILETIME ftLastAccessTime; 
  FILETIME ftLastWriteTime; 
  DWORD    nFileSizeHigh; 
  DWORD    nFileSizeLow; 
  DWORD    dwReserved0; 
  DWORD    dwReserved1; 
  TCHAR    cFileName[ MAX_PATH ]; 
  TCHAR    cAlternateFileName[ 14 ]; 
} WIN32_FIND_DATA, *PWIN32_FIND_DATA; 

二、遍历代码示例

#include "Windows.h"
#include "tchar.h"
#include <iostream>

void FindFile(CONST TCHAR* path)
{
    WIN32_FIND_DATA findFileData; // 保存输出参数
    TCHAR filePath[MAX_PATH] = { 0 };

    if (path[_tcslen(path) - 1] == TEXT('\\'))
    {
        _stprintf_s(filePath, MAX_PATH, TEXT("%s*.*"), path);
    }
    else
    {
        _stprintf_s(filePath, MAX_PATH, TEXT("%s\\*.*"), path);
    }

    HANDLE hFindFile = FindFirstFile(filePath, &findFileData);
    if (hFindFile == INVALID_HANDLE_VALUE)
    {
        _tprintf(TEXT("文件打开失败\n"));
        return;
    }

    do
    {
        // 过滤掉.和..
        if (_tcscmp(findFileData.cFileName, TEXT(".")) == 0
            || _tcscmp(findFileData.cFileName, TEXT("..")) == 0)
        {
            continue;
        }

        TCHAR fullPath[MAX_PATH] = { 0 };
        if (path[_tcslen(path) - 1] == TEXT('\\'))
        {
            _stprintf_s(fullPath, MAX_PATH, TEXT("%s%s"), path, findFileData.cFileName);
        }
        else
        {
            _stprintf_s(fullPath, MAX_PATH, TEXT("%s\\%s"), path, findFileData.cFileName);
        }

        if (findFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) // 目录
        {
            FindFile(fullPath); // 递归
        }
        else // 文件
        {
            _tprintf(TEXT("%s\n"), fullPath);
        }
    } while (FindNextFile(hFindFile, &findFileData));

    FindClose(hFindFile);
}

int _tmain(int argc, TCHAR **argv)
{
    std::locale::global(std::locale("CHS"));

    FindFile(TEXT("D:\\"));

    return 0;
}

Leave a Reply

Your email address will not be published.