搜索按扩展名过滤的文件返回太多结果 [英] Searching files filtering by extension returns too many results

查看:56
本文介绍了搜索按扩展名过滤的文件返回太多结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个必须在Windows OS上管理文件的C ++控制台应用程序.我需要获取具有特定扩展名的文件名的列表".我找到了很多解决方案,最建议的解决方案是以下一种:

I'm developing a C++ console application that has to manage files on Windows OS. I need to obtain a 'list' of file names which have a specific extension. I've found a lot of solutions, the most suggested one is the following one:

HANDLE hFind;
WIN32_FIND_DATA data;

hFind = FindFirstFile("C:\\PWS\\*.sda", &data);
if (hFind != INVALID_HANDLE_VALUE) {
    do {
        cout << data.cFileName << endl;

    } while (FindNextFile(hFind, &data));
    FindClose(hFind);
}

假设我在 C:\\ PWS 文件夹中有这些文件:

Suppose I have these files inside the C:\\PWS folder:

  • f001.sdac
  • f002.sda
  • f003.sdab
  • f004.sda

上面的代码将全部打印出来,而我只需要 f002.sda f004.sda .

The above code prints all of them, while I only need f002.sda and f004.sda.

有任何提示吗?

NB :我不想使用Boost库.

NB: I don't want to use boost library.

推荐答案

我采用的解决方案如下:

The solution I adopted is the following one:

void GetFilesByNameRootAndExtension(const string& dirPath, const string& nameRoot, string& ext, vector<string>& files)
{
    files.clear();

    stringstream ss;
    ss << dirPath << "\\" << nameRoot << "*" << ext;
    string searchKeyS = ss.str();
    const char* searchKey = searchKeyS.c_str();

    WIN32_FIND_DATA data;
    HANDLE hFind = FindFirstFile(searchKey, &data);

    ext = ext.erase(0, 1);
    if (hFind != INVALID_HANDLE_VALUE) {
        do {
            string fN = data.cFileName;
            if (fN.substr(fN.find_last_of(".") + 1) == ext) // filtering by extension
                files.push_back(fN);
        } while (FindNextFile(hFind, &data));
        FindClose(hFind);
    }
}

谢谢大家的提示!

这篇关于搜索按扩展名过滤的文件返回太多结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆