本文介绍了向后读取文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法逐行读取文件,而不必从头开始读取文件,开始向后读?
Is there a way to read a file backwards, line by line, without having to go through the file from the beginning to start reading backwards?
推荐答案
根据注释,一个可能的(非常简单)的替代方法将读取行到向量
。例如:
As per comment, a possible (quite simple) alternative would be read the lines into a vector
. For example:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
int main()
{
std::ifstream in("main.cpp");
if (in.is_open())
{
std::vector<std::string> lines_in_reverse;
std::string line;
while (std::getline(in, line))
{
// Store the lines in reverse order.
lines_in_reverse.insert(lines_in_reverse.begin(), line);
}
}
}
编辑:
根据和的评论, push_back()
会更有效率,但行将在文件顺序,因此反向迭代( reverse_iterator
)或:
As per jrok's and Loki Astari's comments, push_back()
would be more efficient but the lines would be in file order, so reverse iteration (reverse_iterator
) or std::reverse()
would be necessary:
std::vector<std::string> lines_in_order;
std::string line;
while (std::getline(in, line))
{
lines_in_order.push_back(line);
}
这篇关于向后读取文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!