Archive

Posts Tagged ‘Win32’

Iterate Directories & Files in C++

December 9, 2009 Leave a comment

In standard (non-managed) C++ on the Windows platform, traversing a directory / folder tree recursively can be accomplished via the Win32 API.  The following listing is a simple example that displays the name of each file.

#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;
}

Categories: Code, Win32 Tags: , , ,
Follow

Get every new post delivered to your Inbox.