Software & Finance





Visual C++ - List files from a directory - wild card search





The function GetFileList takes searchkey as an input parameter. The search key can use a wild card, like *.txt or *.xml, etc along with the folder name. The return value for the function GetFileList is the collection of strings containing the filenames.

 

FindFirstFile takes searchkey as input parameter and WIN32_FIND_DATA would be a out parameter. The return value is a handle that would be used in subsequent call to FindNextFile. If it is INVALID_HANDLE_VALUE, then there are no files found. FindNextFile returns false, if there are no more files found with the selected search criteria.

 

#include <string>

#include <vector>

#include <windows.h>

 

// searchkey = "c:\\kathir\\*.txt";

int GetFileList(const char *searchkey, std::vector<std::string> &list)

{

    WIN32_FIND_DATA fd;

    HANDLE h = FindFirstFile(searchkey,&fd);

 

    if(h == INVALID_HANDLE_VALUE)

    {

        return 0; // no files found

    }

 

    while(1)

    {

        list.push_back(fd.cFileName);

 

        if(FindNextFile(h, &fd) == FALSE)

            break;

    }

    return list.size();

}

 

 

void main()

{

    std::vector<std::string> list;

    int count = GetFileList("c:\\kathir\\*.txt", list);

 

    // Using Index Based Accessing

    for(int i = 0; i < list.size(); i++)

        MessageBox(list[i].c_str());

 

    // Using const_iterator

    for(std::vector<std::string>::const_iterator it = list.begin();

        it != list.end(); ++it)

    {

        MessageBox(it->c_str());

    }

}