C++ List All Files in a Directory
If you need to do a certain task on all files or folders in a directory, the following code does the job. The following function recursively calls itself for all contained subfolders and prints all the files found. Note that this code will only run on Windows operating system as it uses Win32 API’s, namely FindFirstFile, FindNextFile and FindClose.
GetAllFiles() is called with the path of the base folder from where you want to start the enumeration.
Example Usage: GetAllFiles(“D:”);
Required Headers: <string> and <windows.h>
void GetAllFiles( string sPath )
{
WIN32_FIND_DATA FindFileData;
string sTmpPath = sPath;
sTmpPath += "\\*.*";
HANDLE hFind = FindFirstFile( sTmpPath.c_str(), &FindFileData );
if ( hFind == INVALID_HANDLE_VALUE )
return;
else {
do {
if ( ( FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) ) {
// if directory:
if ( strcmp(".", FindFileData.cFileName ) && strcmp("..", FindFileData.cFileName) ) {
sTmpPath = sPath;
sTmpPath += "\\";
sTmpPath += FindFileData.cFileName;
GetAllFiles( sTmpPath.c_str() );
}
}
else // if file:
{
sTmpPath = sPath;
sTmpPath += "\\";
sTmpPath += FindFileData.cFileName;
cout << sTmpPath << endl;
}
} while ( FindNextFile( hFind, &FindFileData) != 0 );
FindClose( hFind );
}
return;
}

Leave a Reply