Skip to content

Instantly share code, notes, and snippets.

@gszauer
Created June 6, 2013 00:33
Show Gist options
  • Save gszauer/5718458 to your computer and use it in GitHub Desktop.
Save gszauer/5718458 to your computer and use it in GitHub Desktop.
#include <windows.h>
#include <string>
#include <vector>
#include <stack>
#include <iostream>
using namespace std;
// Recursive directory traversal using the Win32 API
bool ListFiles(wstring path, wstring mask, vector<wstring>& files)
{
HANDLE hFind = INVALID_HANDLE_VALUE;
WIN32_FIND_DATA fdata;
wstring fullpath;
stack<wstring> folders;
folders.push(path);
files.clear();
while (!folders.empty())
{
path = folders.top();
fullpath = path + L”\\” + mask;
folders.pop();
hFind = FindFirstFile(fullpath.c_str(), &fdata);
if (hFind != INVALID_HANDLE_VALUE)
{
do
{
if (wcscmp(fdata.cFileName, L”.”) != 0 &&
wcscmp(fdata.cFileName, L”..”) != 0)
{
if (fdata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
folders.push(path + L”\\” + fdata.cFileName);
}
else
{
files.push_back(path + L”\\” + fdata.cFileName);
}
}
}
while (FindNextFile(hFind, &fdata) != 0);
}
if (GetLastError() != ERROR_NO_MORE_FILES)
{
FindClose(hFind);
return false;
}
FindClose(hFind);
hFind = INVALID_HANDLE_VALUE;
}
return true;
}
int main(int argc, char* argv[])
{
vector<wstring> files;
if (ListFiles(L”C:\\source”, L”*”, files))
{
for (vector<wstring>::iterator iter = files.begin(); iter != files.end(); ++iter)
{
wcout << iter->c_str() << endl;
}
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment