Visual C++ - Map files and file time 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 pair of strings containing the filenames and filewritetime.
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::map<std::string, std::string> &map)
{
WIN32_FIND_DATA fd;
HANDLE h = FindFirstFile(searchkey,&fd);
if(h == INVALID_HANDLE_VALUE)
{
return 0; // no files found
}
while(1)
{
char buf[128];
FILETIME ft = fd.ftLastWriteTime;
SYSTEMTIME sysTime;
FileTimeToSystemTime(&ft, &sysTime);
sprintf(buf, "%d-%02d-%02d",sysTime.wYear, sysTime.wMonth, sysTime.wDay);
map[fd.cFileName] = buf;
if(FindNextFile(h, &fd) == FALSE)
break;
}
return map.size();
}
void main()
{
std::map<std::string, std::string> map;
int count = GetFileList("c:\\kathir\\*.txt", map);
// Using const_iterator
for(std::map<std::string, std::string>::const_iterator it = map.begin();
it != map.end(); ++it)
{
MessageBox(it->first.c_str());
MessageBox(it->second.c_str());
}
}
|