2

I'm used to open just one file with the instruction:

ifstream file ("somefile.txt");      //that means that I know the name of my file

Now I have a big directory with a lot of files in it, and my program should open one by one all those files.

How can I do that?

Christophe
  • 61,637
  • 6
  • 65
  • 122

1 Answers1

7

The following methods will all populate a vector with the names of the files in a given directory.

Assume you've defined:

#include <vector>
#include <string>
typedef std::vector<std::string> stringvec;

opendir()/readdir()/closedir() (POSIX)

#include <sys/types.h>
#include <dirent.h>

void read_directory(const std::string& name, stringvec& v)
{
    DIR* dirp = opendir(name.c_str());
    struct dirent * dp;
    while ((dp = readdir(dirp)) != NULL) {
       v.push_back(dp->d_name);
    }
    closedir(dirp);
}

boost_filesystem

#include <boost/filesystem.hpp>

struct path_leaf_string
{
    std::string operator()(const boost::filesystem::directory_entry& entry) const
    {
        return entry.path().leaf().string();
    }
};

void read_directory(const std::string& name, stringvec& v)
{
    boost::filesystem::path p(name);
    boost::filesystem::directory_iterator start(p);
    boost::filesystem::directory_iterator end;
    std::transform(start, end, std::back_inserter(v), path_leaf_string());
}

std::filesystem (C++ 17)

#include <filesystem>

struct path_leaf_string
{
    std::string operator()(const std::filesystem::directory_entry& entry) const
    {
        return entry.path().leaf().string();
    }
};

void read_directory(const std::string& name, stringvec& v)
{
    std::filesystem::path p(name);
    std::filesystem::directory_iterator start(p);
    std::filesystem::directory_iterator end;
    std::transform(start, end, std::back_inserter(v), path_leaf_string());
}

FindFirstFile()/FindNextFile()/FindClose() (Windows)

#include <windows.h>

void read_directory(const std::string& name, stringvec& v)
{
    std::string pattern(name);
    pattern.append("\\*");
    WIN32_FIND_DATA data;
    HANDLE hFind;
    if ((hFind = FindFirstFile(pattern.c_str(), &data)) != INVALID_HANDLE_VALUE) {
        do {
            v.push_back(data.cFileName);
        } while (FindNextFile(hFind, &data) != 0);
        FindClose(hFind);
    }
}

Use one of these, and then you can iterate over the vector and open the files:

#include <iostream>
#include <fstream>

int main()
{
    const std::string directory = "/my/favourite/directory";
    stringvec v;
    read_directory(directory, v);
    for (auto filename : v) {
        std::string path = directory + "/" + filename;
        std::ifstream ifs(path);
        if (ifs) {
            // Read ifs here
        }
        else {
            std::cerr << "Couldn't open " << path << " for reading\n";
        }
    }
}
Martin Broadhurst
  • 8,983
  • 2
  • 27
  • 34