【问题标题】:C++ setting cursor at the exact line in the fileC ++将光标设置在文件中的确切行
【发布时间】:2016-12-30 15:47:57
【问题描述】:

我想用 C++ 从文件中读取一行(但不是第一行)。 有没有聪明的方法来做到这一点?现在我正在考虑使用 getline() 并在循环中继续,但这似乎不是最优化的方式?有任何想法吗? 问候

【问题讨论】:

  • 你可以使用 fseek(),你可以从这里获得帮助cplusplus.com/reference/cstdio/fseek
  • 如果行是可变长度的,那么没有其他方法可以读取行,直到你到达你想要的行。如果它们的长度是固定的,那么你可以寻找linenumber * linelength,考虑到linelength 必须包含换行符。
  • 抱歉,您必须边走边收线。没有系统级的方法可以一次扫描一行。如果必要且可行,您可以为文件编写索引,将已知换行符的位置记录为字节位置。当然,如果不知道您真正想要做什么,我们就无法给出正确的答案。

标签: c++ file fstream


【解决方案1】:

文本行被称为可变长度记录,由于它们的长度可变,您无法轻松定位到文件中的给定行。

一种方法是维护一个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);
}

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

与所有优化一样,也存在妥协。

【讨论】:

    猜你喜欢
    • 2022-11-29
    • 1970-01-01
    • 1970-01-01
    • 2011-03-14
    • 1970-01-01
    • 1970-01-01
    • 2021-09-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多