C 设置光标处的文件中的确切行

C++ setting cursor at the exact line in the file

本文关键字:文件 置光标      更新时间:2023-10-16

我想从C 中的文件中读取一行(但不是第一行)。有什么明智的方法可以实现这一目标吗?现在,我正在考虑使用getline()并继续循环,但这似乎不是最佳的方法?有任何想法吗?问候

文本行被称为可变长度记录,并且由于其可变长度,因此您无法轻松地将其定位到文件中的给定线路。

一种方法是维护文件位置的std::vector。浏览文件,读取每一行并记录其位置:

std::vector<std::streampos> text_line_positions;
// The first line starts at position 0:
text_line_positions.push_back(0);
std::string text;
while (std::getline(my_text_file, text))
{
  const std::streampos position = my_text_file.tellg();
  text_line_positions.push_back(position);
}

您可以从向量检索文件位置:

const std::streampos line_start = text_line_positions[line_number];

编辑1:文本向量
一种更最佳的方法可能是将每条文本行读取到std::vector

std::vector<std::string> file_text;
std::string text;
while (std::getline(my_file, text))
{
  file_text.push_back(text);
}

上述方法的缺点之一是您需要足够的内存来包含文件。
但是,访问时间很快,因为您不需要再次读取文件。

与所有优化一样,涉及妥协。