Home :: Programming :: Code Snippets :: MfcWin :: Enumerating Files In A Directory
[ Enumerating Files In A Directory ]
This code snippet will show how to enumerate the files that are in a certain directory. This is sometimes very useful in some games. One of the famous examples is Half-Life™ where the multiplayer maps are enumerated at runtime. I also use this method for Stoneout where all available maps are shown when you start the game.
This method is really easy. I am using Mfc here, but there is a very similiar function set for the standard Win32 API. Let's simply dive into the code:
//User defined function that does something
//with the files in 'directory'
void EnumFiles(CString directory)
CFileFind fileFinder; // Mfc Class that supports serching for files
char oldDirectory; // Array big enough to hold
// the path of the old current dir
//Save old current directory as we will change to 'directory'
//to enumerate its files. We will be reset at the end of this func.
//CFileFind search only serches files in the current dir.
//'diretcory' will be searched for files. As there are no parameters
//specified, a wildcard search (*.* = every file) will be done.
//FindFile() returns return true if a least one file has been found
bool working = fileFinder.FindFile();
//GetNextFile() returns only true if a file has been found.
//If false is returned, CFileFind has finsihed enumerating files.
working = fileFinder.GetNextFile();
//Do what you want with your file.. GetPathName() returns
//the full path of the currently found file
//Restore old Path
Very easy, isn't it? If you want to search for a specific type of file like Jpegs - have as extension *.jpg or *.jpeg - than replace the first call to FindFile() by this:
bool working = fileFinder.FindFile("*.jp?g");
If you have further questions than simply m@il me. I'll help you out.. Happy Coding!