【问题标题】:c++ reading file using getline and FILE instead of ifstream [duplicate]c ++使用getline和FILE而不是ifstream读取文件[重复]
【发布时间】:2019-10-27 18:07:27
【问题描述】:

我有一个FILE* 对象,我想从中逐行读取。然而,最常见的方法是将目录传递给 ifstream 并在 while 循环中使用 getline(ifstream, line) 逐行读取。

但是我没有目录。我必须与FILE* 合作。是否有getline() 接受FILE* 作为参数?或者,一般来说,c++ 中有另一种方法可以读取带有FILE*的行

C read file line by line 对我不起作用,因为我不在 linux 上。

我也在考虑 ifstream 是否可以接受 FILE 而不是目录,但我不确定这一点。谁能确认一下?

【问题讨论】:

  • 您链接到的答案中有各种其他便携式解决方案,这些有什么问题?
  • 你可以使用 boost::filesystem::ifstream 作为替代
  • @camp0 我很感激一个例子,因为我是新手。
  • 从 fgets 构建一个 getline 克隆并不难。一点内存分配就搞定了……

标签: c++ file io getline


【解决方案1】:
std::vector<std::string> getFileAsLines(FILE *file) {
  std::vector<std::string> out;
  int currentIn = fgetc(file);
  std::string currentLine;

  while(currentIn != EOF) {
    if (currentIn == '\n') {
      out.push_back(currentLine);
      currentLine = std::string();
    } else {
      currentLine += (char)currentIn;
    }

    currrentIn = fgetc(file);
  }
  out.Push_back(currentLine);
  return out;
}

没有测试过,但想法应该通过

【讨论】:

  • 在您的 while 条件下,它应该是 &amp;&amp;and 而不是 AND
  • @Narase 作为终止,while(line = getNextLine(File*file) != NULL) 应该可以正常工作吗?因为“out”最初是空的
  • 不,空字符串不是 NULL,因为它不是指针。看起来你来自 Java/C#。我编辑了该函数,使其将整个文件作为行列表返回
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-17
  • 1970-01-01
  • 2014-11-03
  • 2016-07-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多