Under linux fuzzy search files by file name

Sample code is as follows:

#include <fnmatch.h>
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <vector>
#include <string>
#include <iostream>

using namespace std;


vector<string> WildcardSearch(const char* pattern,const char* filePath)
{
    vector<string> res;
    struct dirent *entry;
    DIR *dir;   
    int ret;

    dir = opendir(filePath);
    if(dir != NULL)
    {
        while((entry = readdir(dir)) != NULL)
        {
            ret = fnmatch(pattern,entry->d_name,FNM_PATHNAME | FNM_PERIOD);
            if(ret == 0)
            {
                res.push_back(entry->d_name);               
            }
            else
            {
                continue;
            }
        }
    
    }

    closedir(dir);
    return res;
}


int main(int argc,char*argv[])
{
    vector<string> tmp;
    char* pattern = argv[1];
    char* path = argv[2];
    
    tmp = WildcardSearch(pattern,path);

    for(int i=0;i<tmp.size();i++)
        cout<<tmp[i]<<endl;

    return 0;
}

E.g:

./test "2018-*.bmp" ./path

Guess you like

Origin www.cnblogs.com/chay/p/11353577.html