Windows fnmatch替代品

时间:2016-03-08 20:49:51

标签: c++ windows visual-studio-2010

我在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 link找到一个。{ / p>

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

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

2 个答案:

答案 0 :(得分:2)

感谢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;
    }

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

答案 1 :(得分:1)

看起来PathMatchSpec就是你的家伙。