View the contents of a directory source code

This snippet submitted by finnepower on 2005-08-06. It has been viewed 33482 times.
Rating of 6.9 with 160 votes

 This is how you get the contents of a directory in Windows with C++. It's useful if your program needs to know stuff about your files.

#include <iostream>
#include <windows.h>

using namespace std;

int main()
{
WIN32_FIND_DATA FindFileData; 
HANDLE hFind = INVALID_HANDLE_VALUE; 
char DirSpec[MAX_PATH]; // directory specification 

cout<<"Path: ";
cin.get(DirSpec, MAX_PATH);
cout<<"\n";
strncat(DirSpec, "\\*", 3);
hFind = FindFirstFile(DirSpec, &FindFileData);

	if(hFind == INVALID_HANDLE_VALUE)
	{
	cout<<"Error: invalid path\n";
	}

cout<<FindFileData.cFileName<<"\n";

	while(FindNextFile(hFind, &FindFileData) != 0)
	{
	cout<<FindFileData.cFileName<<"\n";
	}

FindClose(hFind);

return 0;
}




More C and C++ source code snippets

Add a snippet!