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);
}
上述方法的缺点之一是您需要足够的内存来包含文件。
但是,访问时间很快,因为您不需要再次读取文件。
与所有优化一样,都涉及妥协。
我想用 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);
}
上述方法的缺点之一是您需要足够的内存来包含文件。
但是,访问时间很快,因为您不需要再次读取文件。
与所有优化一样,都涉及妥协。