Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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

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 = 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);
}

This gives you a vector with all filenames in a directory. It only works on Windows of course.


João Augusto noted in an answer:

Don't forget to check after FindClose(hFind) for:

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

It's especially important if scanning on a network.

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

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.

C++17 includes a standard way of achieve that

http://en.cppreference.com/w/cpp/filesystem/directory_iterator

#include <fstream>
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;

int main()
{
    fs::create_directories("sandbox/a/b");
    std::ofstream("sandbox/file1.txt");
    std::ofstream("sandbox/file2.txt");
    for(auto& p: fs::directory_iterator("sandbox"))
        std::cout << p << '\n';
    fs::remove_all("sandbox");
}

Possible output:

sandbox/a
sandbox/file1.txt
sandbox/file2.txt

Another alternative is -

  1. system("dir | findstr \".bmp\" > temp.txt ");
  2. Now read temp.txt line by line to get all filenames.

Why not use glob()?

glob_t glob_result;
glob("/foo/bar/*",GLOB_TILDE,NULL,&glob_result);
for(unsigned int i=0;i<glob_result.gl_pathc;++i){
  cout << glob_result.gl_pathv[i] << endl;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top