Home > Enterprise >  (C ) How do i read all files of a directory and put their contents in a vector/std::list?
(C ) How do i read all files of a directory and put their contents in a vector/std::list?

Time:01-12

The contents of the files are line by line and go in a "Schedule" struct. My objective is to stock these schedules in .txt files so they don't disappear after the end of execution, and to stock the structs in a vector or a list when i execute it again, by reading all files of a separated folder. I have no idea how to do this.

I supposed i could use getline() for a folder but even if it worked it would probably just give me the file names. That could work in a way, but getline() doesn't work like that.

CodePudding user response:

I would use a std::filesystem::directory_iterator and a std::vector<std::filesystem::directory_entry> (or the often just a tad smaller std::filesystem::path). Populating the vector will then be pretty straight forward. Example:

#include <iostream>
#include <filesystem>
#include <vector>

class Schedule {
public:
    void populate_from_dir(const std::filesystem::path& path) {
        dirents.clear();

        dirents.insert(
            dirents.end(),
            std::filesystem::directory_iterator(path),   // begin
            std::filesystem::directory_iterator{}        // end iterator
        );
    }

    void print(std::ostream& os = std::cout) const {
        for(auto& dent : dirents) {
            os << dent << '\n';
        }
    }

private:
    std::vector<std::filesystem::directory_entry> dirents;
};

int main() {
    Schedule s;
    s.populate_from_dir(".");
    s.print();
}

CodePudding user response:

The same as @Ted above.

But we can simplify a bit:

int main()
{
    namespace fs = std::filesystem;
    std::vector<fs::directory_entry> dirents{fs::directory_iterator("."), fs::directory_iterator{}};

    for (auto const& dir: dirents) {
        std::cout << dir.path() << "\n";
    }
}
  • Related