如何在C ++中将所有文件和目录加载到内存

时间:2018-08-07 13:58:18

标签: c++

我正在做一个程序来管理目录及其内容,我想在确定的目录中运行程序,并将该目录以及所有包含的文件加载到内存中。并在蜜蜂成功的情况下返回true。 示例我有一个包含3个文件(center.txt,main.csv,re.txt)和2个文件夹(1、2)的文件夹,其中文件夹1是文件(file.txt)。我想将此加载到内存,文件和目录(以及确定目录包含的文件)中。  我想预先运行目录,然后在找到文件时将其加载到内存中。

我有这段代码来列出文件。我现在想加载到内存中

void Load(const string &path) {

    DIR *pDIR;
    ifstream inn;
    string   str;
    string c = path;
    const char *f = c.c_str();
    struct dirent *entry;
    if (pDIR = opendir(f)) {
        while (entry = readdir(pDIR)) {
                cout << entry->d_name << "\n";

        }
        closedir(pDIR);
    }
}

1 个答案:

答案 0 :(得分:0)

一段代码以递归方式遍历,并将文件内容作为字符串加载到map中。希望这会有所帮助:

#include <dirent.h>
#include <fstream>
#include <iostream>
#include <map>

std::map<std::string, std::string> Load(const std::string& path) {
    // Map with file name and contents
    std::map<std::string, std::string> files;
    DIR* pDIR;
    const char* f = path.c_str();

    pDIR = opendir(f);
    if (!pDIR) {
        return files;
    }

    struct dirent* entry;
    while ((entry = readdir(pDIR))) {
        std::string fileName = std::string(entry->d_name);
        // Skip current dir and parent dir
        if (fileName == "." || fileName == "..") {
            continue;
        }

        // Add current path to the filename
        fileName = path + "/" + fileName;

        // This is directory, load recursively
        if (entry->d_type == DT_DIR) {
            std::cout << "Found directory: " << fileName << std::endl;
            auto ret = Load(fileName);

            // Merge files
            files.insert(ret.begin(), ret.end());
            continue;
        }

        std::cout << "Found file: " << fileName << std::endl;

        // Read file contents and add it to map
        std::ifstream file(fileName);
        std::string content((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
        files[fileName] = content;
    }
    closedir(pDIR);

    return files;
}

int main(int argc, char** argv) {
    auto files = Load(".");
    return 0;
}