tags:

views:

546

answers:

6

Hi All,

I was wondering if there's an easy way in C++ to read a number of file names from a folder containing many files. They are all bitmaps if anyone is wondering.

I don't know much about windows programming so I was hoping it can be done using simple C++ methods.

Thanks!

+3  A: 

I think you're looking for FindFirstFile() and FindNextFile()

-John

John T
+1  A: 

Hi Anthony,

I recommend you can use the native Win32 FindFirstFile() and FindNextFile() functions. These give you full control over how you search for files. This are simple C APis and are not hard to use.

Another advantage is that Win32 errors are not hidden or made harder to get at due to the C/C++ library layer.

RGR

Foredecker
+2  A: 

You could also use the POSIX opendir() and readdir() functions. See this manual page which also has some great example code.

slacy
+7  A: 

Boost provides a basic_directory_iterator which provides a C++ standard conforming input iterator which accesses the contents of a directory. If you can use Boost, then this is at least cross-platform code.

chrish
+2  A: 

Just had a quick look in my snippets directory. Found this:

vector<CStdString> filenames;
CStdString directoryPath("C:\\foo\\bar\\baz\\*");

WIN32_FIND_DATA FindFileData; 
HANDLE hFind = INVALID_HANDLE_VALUE;

hFind = FindFirstFile(directoryPath, &FindFileData);

if(hFind  != INVALID_HANDLE_VALUE)
{
 do
 {
        if(FindFileData.dwFileAttributes != FILE_ATTRIBUTE_DIRECTORY)
        filenames.push_back(FindFileData.cFileName);
 } while(FindNextFile(hFind, &FindFileData));

 FindClose(hFind);
}

Gives you a vector with all filenames in a directory. Only works on windows of course.

drby
A: 

If using hackingwords solution, don't forget to check after

FindClose(hFind)

for

DWORD dwError = GetLastError();
if (dwError != ERROR_NO_MORE_FILES) 
{
  // Errot happened        
}

It's especially important if scanning on a network... :)

João Augusto