{steinsoft.net}
 
 
 
 
 
Home/News
Code Snippets
Board
Projects
What's That?
I am using it actively
I planning to use/learn it
I don't plan to lean/use it
5th option
Leipzig
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[512]; // 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.
   GetCurrentDirectory(oldDirectory,512);
 
   //'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();
  
   while(working)
   {
      //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
      DoSomethingWithFile(fileFinder.GetPathName());
   }
 
   //Restore old Path
   SetCurrentDirecotory(oldDirectory);
}

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!

 Last edited 2002-12-08 00:38:48 by André Stein - printable version
» copyright by andré stein
» using stCM v1.0
» steinsoft.net revision 5.0