How to filter out the result to get only file names in output result linux in c++98

  absolute-path, c++, linux, string, vector

The current code snippet will match the pattern and list out all matching pattern files present in directory specified where in below example File is the pattern to be matched*, here the output will be listed with absolute path like below.

    /home/downloads/File1
    /home/downloads/File2
    /home/downloads/File3
    /home/downloads/File4

wherein, I am looking for only Filename to be listed, i,e like given below:

File1
File2
File3
File4

c++ code below:

    #include <glob.h>
    #include <cerrno>
    #include <cstring>
    #include <iostream>
    #include <stdexcept>
    #include <string>
    #include <vector>
    using namespace std;
    vector<string> glob(const string& pattern) {
        glob_t glob_result = {0}; // zero initialize
        // do the glob operation
        int return_value = ::glob(pattern.c_str(), GLOB_TILDE, NULL, &glob_result);
        if(return_value != 0) throw runtime_error(strerror(errno));
        // collect all the filenames into a std::vector<std::string>
        // using the vector constructor that takes two iterators
        vector<string> filenames(
            glob_result.gl_pathv, glob_result.gl_pathv + glob_result.gl_pathc);
        // cleanup
        globfree(&glob_result);
        
        // done
        return filenames;
    }
    int main() {
        try { // catch exceptions
               vector<string> res = glob("/home/downloads/File*"); // files with an "File" in the filename
               for(size_t i = 0; i< res.size(); ++i)
                  std::cout << res[i] << 'n';
            } catch(const exception& ex) {
            cerr << ex.what() << endl;
        }
    }

 

Source: Windows Questions C++

LEAVE A COMMENT