Thread: Filter directory search results.

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered Abuser Loic's Avatar
    Join Date
    Mar 2007
    Location
    Sydney
    Posts
    115

    Filter directory search results.

    Hi all, I have a function that returns the contents of a directory in a string vector. It works perfectly but what I want to do is filter out the results for a certain file type. I just wanted to know if there was anything already available to do this? Or would I just have to take the last 4 characters of the string and compare it? Below is the function I am using to get the contents of a directory.

    Code:
    int getdir (std::string dir, std::vector<std::string> &files)
    {
        DIR *dp;
        struct dirent *dirp;
        if((dp  = opendir(dir.c_str())) == NULL) {
            std::cout << "Error(" << errno << ") opening " << dir << std::endl;
            return errno;
        }
    
        while ((dirp = readdir(dp)) != NULL) {
            files.push_back(std::string(dirp->d_name));
        }
        closedir(dp);
        return 0;
    }

    EDIT:
    I have come up with this... but its not perfect… but it works…
    so again, is there a better way to do this?


    Code:
    int getdir (std::string dir, std::vector<std::string> &files, std::string filetype)
    {
        DIR *dp;
        struct dirent *dirp;
        if((dp  = opendir(dir.c_str())) == NULL) {
            std::cout << "Error(" << errno << ") opening " << dir << std::endl;
            return errno;
        }
    
        while ((dirp = readdir(dp)) != NULL) {
            if (std::string(dirp->d_name).find(filetype)!=std::string::npos)
               files.push_back(std::string(dirp->d_name));
        }
        closedir(dp);
        return 0;
    }
    Last edited by Loic; 08-17-2008 at 08:51 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Logical errors with seach function
    By Taka in forum C Programming
    Replies: 4
    Last Post: 09-18-2006, 05:20 AM
  2. Binary Search Trees Part III
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 10-02-2004, 03:00 PM
  3. Big help in Astar search code...
    By alvifarooq in forum C++ Programming
    Replies: 6
    Last Post: 09-24-2004, 11:38 AM
  4. linear search for structure (record) array
    By jereland in forum C Programming
    Replies: 3
    Last Post: 04-21-2004, 07:31 AM