利用C++读取文本最后一行信息

当文本数据太大的时候,如果想要获取的信息在最后一行,就需要从最后一行获取信息。下面是一个实现该任务的代码。

例子文本中保存的数据如下,先需要获取, 最后一行第一个数字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

运行结果如下
运行结果

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值