Read file names from a directory

31,324

Solution 1

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.

Solution 2

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

Solution 3

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

Solution 4

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.

Solution 5

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

Share:
31,324
Tony R
Author by

Tony R

Updated on July 05, 2022

Comments

  • Tony R
    Tony R almost 2 years

    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.