当文本数据太大的时候,如果想要获取的信息在最后一行,就需要从最后一行获取信息。下面是一个实现该任务的代码。
例子文本中保存的数据如下,先需要获取, 最后一行第一个数字3,因为其记录了文本总共的行数信息。本例子先将文件流定位到文件末尾,然后依次向前进行换行符查询,找到第一个换行符,便找到最后一行的启始部分。从程序运行结果看,下面的文本大小一共为30字节,在每一行的末尾均有一个换行符。
0 aaa
1 bbbb
2 cccccc
3 ddddd
#include<vector>
#include <fstream>
#include <iostream>
#include <sstream>
int main( int argc, const char** argv )
{
std::string file = "./test.txt";
std::ifstream ifs(file.c_str(), std::fstream::in);
if(!ifs)
std::cout << "Read file failed!" << std::endl;
//obtain size of file in Byte
ifs.seekg(0, ifs.end);
int length = ifs.tellg();
std::cout << "length: " << length << std::endl;
std::string line;
//check '\n' from second character because the last character is '\n'
int index = -2;
int linenum = 0;
while(length)
{
char c;
ifs.seekg (index, ifs.end);
ifs.get(c);
//check '\n' from end to begin
if(c == '\n')
{
//get the the last line when finding its corresponding beginning
std::getline(ifs, line);
//convet characters to int through istringstream class provided in c++
std::istringstream iss(line);
iss >> linenum;
break;
}
length--;
index--;
}
std::cout << "line num: " << linenum << std::endl;
}
利用g++编译
g++ test.cpp -O3 -o test
运行结果如下