1
C - C++ / Re: How to get a list of files in a directory
« on: July 22, 2012, 07:56:48 am »Code: (c++) [Select]
#include <windows.h>
#include <string>
#include <iostream>
#include <list>
using namespace std;
void GetFileListing(list<string>& listing, string directory, string fileFilter, bool recursively=true)
{
if (recursively)
GetFileListing(listing, directory, fileFilter, false);
directory += "\\";
WIN32_FIND_DATA FindFileData;
HANDLE hFind = INVALID_HANDLE_VALUE;
string filter = directory + (recursively ? "*" : fileFilter);
hFind = FindFirstFile(filter.c_str(), &FindFileData);
if (hFind == INVALID_HANDLE_VALUE)
{
DWORD dwError = GetLastError();
if (dwError!=ERROR_FILE_NOT_FOUND)
{
cout << "Invalid file handle for filter "<<filter<<". Error is " << GetLastError() << endl;
}
}
else
{
if (!recursively)
{
listing.push_back(directory + string(FindFileData.cFileName));
}
while (FindNextFile(hFind, &FindFileData) != 0)
{
if (!recursively)
{
listing.push_back(directory + string(FindFileData.cFileName));
}
else
{
if ((FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)>0 && FindFileData.cFileName[0]!='.')
{
GetFileListing(listing, directory + string(FindFileData.cFileName), fileFilter);
}
}
}
DWORD dwError = GetLastError();
FindClose(hFind);
if (dwError != ERROR_NO_MORE_FILES)
{
cout << "FindNextFile error. Error is "<< dwError << endl;
}
}
}
int main(int argc, char* argv[])
{
list<string> listing;
GetFileListing(listing, "G:", "*.*");
for(list<string>::iterator it = listing.begin(); it!=listing.end();++it)
{
cout << *it << endl;
}
getchar();
return 0;
}
Enjoy