Monday, May 24, 2010

C++: What's the easiest way to put the filenames of a directory in an array?

I'm using a Microsoft Visual Studio 2005 MFC application.





I would like go through a directory, reading file names. If the file name (not including extension, of course) is three letters long, I would like to put that filename into an array, and then move on to the next file to test whether it belongs in the array, until I've reached the end of the directory. What is the easiest way to do this? Should I use a CFileFind, or is there a more efficient method?





Specific examples would be appreciated. Also, please keep in mind that this is an MFC application: NOT a console application.





Thanks!

C++: What's the easiest way to put the filenames of a directory in an array?
Doesn't matter if console or not, you still can use console techniques, just need to modify to fit your instance.


for the cout, replace that with your array, I would recommend a dynamic array or better yet use a vector class so you don't have to worry about allocation





CFileFind finder;


BOOL bWorking = finder.FindFile("*.*");


while (bWorking)


{


bWorking = finder.FindNextFile();


cout %26lt;%26lt; (LPCTSTR) finder.GetFileName() %26lt;%26lt; endl;


}
Reply:Ugh...Truthfully, I'd recommend that you program Windows with the Windows API instead of using the stupid Microsoft MFC or Borland VCL frameworks because they both produce incredibly bloated, slow code. They also don't teach you how to really program the operating system since they are bloated, slow wrappers which EVENTUALLY calls the Windows API functions. Anyways...





The 1st thing that comes to mind is the size of your array. Normally, you would have to write code so that the allocated memory block or array for the file names is large enough for a good number of file names (this can waste memory), or you have to write code that will dynamically allocate another block of memory when your 1st buffer gets full. Something to keep in mind...





As far as getting the file names, do something like this:


1) Call CFileFind::FindNextFile(). Set a flag if it returns 0 (last file in directory).


http://msdn2.microsoft.com/en-us/library...





2) Call CFileFind::GetFileName().


http://msdn2.microsoft.com/en-us/library...





3) In a loop, read the file name and copy it to array/memory block if necessary.





4) If the flag wasn't set, go back to step 1.


No comments:

Post a Comment