【问题标题】:(C++) How do i read all files of a directory and put their contents in a vector/std::list?(C++) 我如何读取目录的所有文件并将它们的内容放入向量/std::list 中?
【发布时间】:2023-01-12 04:14:43
【问题描述】:

文件的内容是逐行的,并进入“计划”结构。我的目标是将这些计划存储在 .txt 文件中,这样它们在执行结束后不会消失,并在我再次执行它时通过读取单独文件夹的所有文件将结构存储在向量或列表中。 我不知道该怎么做。

我想我可以将 getline() 用于文件夹,但即使它有效,它也可能只会给我文件名。这在某种程度上是可行的,但 getline() 并不是那样工作的。

【问题讨论】:

  • 很遗憾听到您“不知道如何执行此操作”,不幸的是 Stackoverflow 不是 C++ 教程站点或帮助站点。我们只回答具体的问题。您将需要首先尝试自己实施您的程序,然后提出实施过程中出现的任何问题。
  • Ted 的回答很准确,一般来说,与文件/文件夹管理相关的所有内容都可以在en.cppreference.com/w/cpp/filesystem 中找到。 cppreference 是一个值得了解的好站点,因为您可以在那里找到所有 C++ 和标准库信息(包括示例)。

标签: c++ file vector getline


【解决方案1】:

与上面的@Ted 相同。

但是我们可以稍微简化一下:

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() << "
";
    }
}

【讨论】:

    【解决方案2】:

    我会使用 std::filesystem::directory_iteratorstd::vector&lt;std::filesystem::directory_entry&gt;(或者通常稍微小一点的std::filesystem::path)。填充 vector 将非常简单。例子:

    #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 << '
    ';
            }
        }
    
    private:
        std::vector<std::filesystem::directory_entry> dirents;
    };
    
    int main() {
        Schedule s;
        s.populate_from_dir(".");
        s.print();
    }
    

    【讨论】:

    • Ted 在功能上是一个很好的例子。然而,从设计的角度来看,我认为这不应该是 Schedule 类本身,而更像是一个调度加载器/工厂。我倾向于将文件/io 与类分开(去年是文件,今天是数据库,明天是互联网流)。我也知道我偏离了 OP 最初的问题;)
    • @PepijnKramer 是的,你可能是对的。恐怕它可能会使答案膨胀并模糊一些有趣的部分。也许不是...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-14
    • 1970-01-01
    • 2014-04-16
    相关资源
    最近更新 更多