【问题标题】:Reading a file line by line with boost filesystem C++使用boost文件系统C++逐行读取文件
【发布时间】:2016-01-17 07:51:37
【问题描述】:

我正在使用 boost::filesystem 库打开具有特定路径 file_path 的文件:

 fs::ifstream file(file_path);
    string str;
    vector<string> filenames;
    while(getline(file, str)){
        filenames.push_back(str);
    }

此代码是从常规 C++ 代码改编而来的,没有经过增强。我最初正在阅读放置在当前目录中的文件,但我必须编辑路径。现在看来 getline 无法正常工作。是否有 getline 的 boost 替代方法,以便我可以逐行解析文件并将它们读入向量中?

谢谢!

【问题讨论】:

  • 如果你的问题是在更改file_path时开始的,可能是打开文件没有成功。
  • “无法正常工作”是什么意思?您需要发布代码、预期行为和实际行为。

标签: file parsing boost filesystems


【解决方案1】:

boost::filesystem::ifstream 只是另一个输入流,所有标准算法都适用于它,就像它们适用于std::ifstream 一样。 std::getline 也可以使用它。

【讨论】:

    【解决方案2】:

    上面的答案是绝对正确的。如果有人想要完整的代码:

    boost::filesystem::ifstream fileHandler(fileName);
    string line;
    while (getline(fileHandler, line)) {
        cout << line << endl;
    }
    

    【讨论】:

      猜你喜欢
      • 2014-06-21
      • 2012-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多