如何在C ++文件列表中按文件打开文件?

时间:2017-11-05 17:58:29

标签: c++ file

我以前用指令只打开一个文件:

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

现在我有一个包含大量文件的大目录,我的程序应该逐个打开所有这些文件。

我该怎么做?

1 个答案:

答案 0 :(得分:4)

以下方法将使用给定目录中的文件名填充向量。

假设您已定义:

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

使用其中一个,然后您可以迭代向量并打开文件:

#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";
        }
    }
}