首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Windows fnmatch替代

Windows fnmatch替代
EN

Stack Overflow用户
提问于 2016-03-08 20:49:51
回答 2查看 2K关注 0票数 1

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

代码语言:javascript
复制
    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 link找到一个。

是否有一个完全相同的fnmatch替代函数?

如何使这段代码在不中断逻辑的情况下在VS2012中编译和运行?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-03-08 20:55:53

看来PathMatchSpec是你的人。

票数 2
EN

Stack Overflow用户

发布于 2016-03-08 21:17:24

感谢SergeyA的帮助。这是我最后的解决办法,以防将来有人需要.

代码语言:javascript
复制
#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;
    }

如果有什么可以改进的话请评论..。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35877738

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档