视窗fnmatch替代品

Windows fnmatch substitute

本文关键字:替代品 fnmatch 视窗      更新时间:2023-10-16

我在 Linux 中有以下代码,用于查找与给定通配符匹配的文件:

    std::vector<std::string> listFilenamesInPath(std::string wildcard = "*", std::string directory = "./")
    {
        std::vector<std::string> result;
        DIR* dirp = opendir(directory.c_str());
        if (dirp)
        {
            while (true)
            {
                struct dirent* de = readdir(dirp);
                if (de == NULL)
                    break;
                if (fnmatch(wildcard.c_str(), de->d_name, 0))
                    continue;
                else
                    result.push_back (std::string(de->d_name));
            }
            closedir(dirp);
        }
        std::sort(result.begin(), result.end());
        return result;
    }

我正在将此代码移植到 Windows,发现fnmatch不可用(dirent也不可用,但我可以根据以下 SO 链接找到一个。

有没有做完全相同事情的 fnmatch 替代函数?

如何在不破坏逻辑的情况下使此代码在VS2012中编译和运行?

感谢谢尔盖的帮助。这是我的最终解决方案,以防将来有人需要......

#ifdef _WIN32
#include "dirent.h"
#include "windows.h"
#include "shlwapi.h"
#else
#include <dirent.h>
#include <fnmatch.h>
#endif
    std::vector<std::string> listFilenamesInPath(std::string wildcard = "*", std::string directory = "./")
    {
        std::vector<std::string> result;
        DIR* dirp = opendir(directory.c_str());
        if (dirp)
        {
            while (true)
            {
                struct dirent* de = readdir(dirp);
                if (de == NULL)
                    break;
#ifdef _WIN32
            wchar_t wname[1024];
            wchar_t wmask[1024];
            size_t outsize;
            mbstowcs_s(&outsize, wname, de->d_name, strlen(de->d_name) + 1);
            mbstowcs_s(&outsize, wmask, wildcard.c_str(), strlen(wildcard.c_str()) + 1);
            if (PathMatchSpecW(wname, wmask))
                result.push_back (std::string(de->d_name));
            else
                continue;
#else
                if (fnmatch(wildcard.c_str(), de->d_name, 0))
                    continue;
                else
                    result.push_back (std::string(de->d_name));
#endif
            }
            closedir(dirp);
        }
        std::sort(result.begin(), result.end());
        return result;
    }

请评论是否可以改进...

看起来 PathMatchSpec 是你的人。