繁体   English   中英

Windows fnmatch替代品

[英]Windows fnmatch substitute

我在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中运行?

感谢SergeyA的帮助。 如果有人将来需要,这是我的最终解决方案...

#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是你的家伙。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM