C 设置光标处的文件中的确切行
C++ setting cursor at the exact line in the file
我想从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);
}
上述方法的缺点之一是您需要足够的内存来包含文件。
但是,访问时间很快,因为您不需要再次读取文件。
与所有优化一样,涉及妥协。
相关文章:
- 在读取文件后重置句柄
- 使用内置的Windows方法获取文件夹的内容
- C++ 从资源文件更改光标时出错
- 如何在内置或用户定义的文件夹中检查Imapifolder
- 大多数内存有效的方法是在C 中转置大文件
- 使用代码移动光标并打开文件夹
- C 设置光标处的文件中的确切行
- 即使不满足条件,也会重置文本文件.(C++)
- 从文件读取时如何使用运算符后将光标移动到下一行">>"
- 在 C++ 中设置内置 exe 的 Windows 文件详细信息
- 如何在 C++ 中使用更改光标输入和输出二进制文件
- 将文件拖到窗口中时设置光标
- Qt鼠标光标重置
- 文件异常和光标移动c++
- 如何阻止 fin "file pointer"重置回文件 c++ 的开头?
- 如何从最后一个光标位置读取文件
- 如何在二进制文件中设置内置版本号
- 在jam文件中指定Boost.build内置功能
- 正在重置文件安全性以继承MoveFile()操作之后的文件
- 如果cout、cerr和clog的rdbuf已更改为重定向到文件,是否有必要重置它们