如何使用 Win API 获取文件夹中的文件列表(带过滤器)

How to get a list of files (with filter) in folder with Win API

本文关键字:列表 文件 过滤器 Win 何使用 API 获取 文件夹      更新时间:2023-10-16

我在互联网上搜索了有关获取目录中的文件列表的信息,但大多数答案都需要提升库。所以我为那些不想添加任何第三方库的人提出这个问题。

那么如何获取目录中的文件列表呢?我们还可以决定要获取的文件的模式(像所有文件一样,仅txt文件,文件名中包含特定文本的文件,...另外决定是否在子文件夹中搜索。

编辑:我看到这个问题被降级了,也许是因为我没有具体说明这个问题是针对 Win 32 而不是一般C++(我最近才意识到,当我说C++时,没有必要意味着 Win API(。

无论如何,在这个问题上,我的意思是要求 Win API。当然,一般C++是受欢迎的(因为它也可以与Windows一起使用,更好的是跨平台(。

C++17 有一个 std::filesystem::d irectory_iterator,可以用作

#include <string>
#include <iostream>
#include <filesystem>
namespace fis = std::filesystem;
int main()
{
    std::string dir_path = "path_to_dir";
    for (auto & i : fis::directory_iterator(dir_path))
        std::cout << i << std::endl;
}

此外,std::filesystem::recursive_directory_iterator 也可以迭代子目录。

可以使用dirent.h,它也适用于Windows:

DIR *dir;
struct dirent *s_dir;
if ((dir = opendir ("c:\programs\")) != NULL) {
  /* print all the files and directories */
  while ((s_dir = readdir (dir)) != NULL) {
    printf ("%sn", s_dir->d_name);
  }
  closedir (dir);
} else {
  /* could not open directory */
  perror ("");
  return EXIT_FAILURE;
}

所以这是函数

void GetSubfolderInDirectory(std::vector<TCHAR*> *lstFileOut, const TCHAR* szPath)
{
    HANDLE hFind;
    WIN32_FIND_DATA findData;
    TCHAR szCurrentDir[MAX_PATH];
    _tcscpy_s(szCurrentDir, MAX_PATH, szPath);
    TCHAR szPatternDir[MAX_PATH];
    _tcscpy_s(szPatternDir, MAX_PATH, szCurrentDir);
    _tcscat_s(szPatternDir, MAX_PATH, _T("/*"));
    TCHAR* szFullPath;
    bool bIsDirectory;
    if ((hFind = FindFirstFile(szPatternDir, &findData)) == INVALID_HANDLE_VALUE)
    {
        return;
    }
    do {
        bIsDirectory = (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
        if (bIsDirectory)
        {
            if (findData.cFileName[0] == '.')
            {
                continue;
            }
            szFullPath = (_TCHAR*)malloc(_MAX_PATH * sizeof(_TCHAR));
            _tcscpy_s(szFullPath, MAX_PATH, szCurrentDir);
            _tcscat_s(szFullPath, MAX_PATH, _T("\"));
            _tcscat_s(szFullPath, MAX_PATH, findData.cFileName);
            lstFileOut->push_back(szFullPath);
        }
    } while (FindNextFile(hFind, &findData));
    FindClose(hFind);
}
void GetFilesInDirectory(std::vector<TCHAR*> *lstFileOut, const TCHAR* szPath, 
    const TCHAR* szPattern, bool bSearchSub)
{
    HANDLE hFind;
    WIN32_FIND_DATA findData;
    TCHAR szCurrentDir[MAX_PATH];
    _tcscpy_s(szCurrentDir, MAX_PATH, szPath);
    TCHAR szPatternDir[MAX_PATH];
    _tcscpy_s(szPatternDir, MAX_PATH, szCurrentDir);
    _tcscat_s(szPatternDir, MAX_PATH, _T("/"));
    _tcscat_s(szPatternDir, szPattern);
    if ((hFind = FindFirstFile(szPatternDir, &findData)) == INVALID_HANDLE_VALUE)
        return; /* No files found */
    TCHAR* szFullPath;
    bool bIsDirectory;
    do {
        szFullPath = (_TCHAR*)malloc(_MAX_PATH * sizeof(_TCHAR));
        _tcscpy_s(szFullPath, MAX_PATH, szCurrentDir);
        _tcscat_s(szFullPath, MAX_PATH, _T("\"));
        _tcscat_s(szFullPath, MAX_PATH, findData.cFileName);
        bIsDirectory = (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
        if (findData.cFileName[0] == '.')
        {
            free(szFullPath);
            continue;
        }
        if (bIsDirectory)
        {
            continue;
        }
        else
        {
            lstFileOut->push_back(szFullPath);
        }
    } while (FindNextFile(hFind, &findData));
    FindClose(hFind);
    if (bSearchSub)
    {
        std::vector<TCHAR*> lstDir;
        GetSubfolderInDirectory(&lstDir, szCurrentDir);
        int nFolderCount = lstDir.size();
        for (int i = 0; i < nFolderCount; i++)
        {
            GetFilesInDirectory(lstFileOut, lstDir[i], szPattern, bSearchSub);
        }
    }
}

这是如何使用

TCHAR szCrtPath[MAX_PATH];
TCHAR szCrtPattern[MAXBYTE];
_tcscpy_s(szCrtPattern, _T("*.*"));
_tcscpy_s(szCrtPath, _MAX_PATH, _T("D:\MyFolder"));
vector<TCHAR*> lstFile;
GetFilesInDirectory(&lstFile, szCrtPath, szCrtPattern, true);

关于模式的一些解释

*.* // Get all files
*.txt // Get txt file only
*sometext* // Get file with "sometext" in size file name

也许有更好的方法来获取目录中的所有子文件夹(函数GetSubfolderInDirectory(。