C++倒序按行读取文件

前言:

        因为有些文件是以追加方式进行写入的,最新数据在最后一行,在展示数据时阅读习惯是从最新的开始看,所以诞生了倒序按行读取文件的需求。

如文件:

第一行
第二行
第三行

期望读取效果:

第三行
第二行
第一行

源码使用的C++11: 

#include <iostream>
#include <fstream>
#include <string.h>
#include <vector>

using namespace std;


int main(int argc, char** argv)
{
	vector<string> lines;
	string line;

	char x;
	ifstream f("/root/temp.txt", ios::ate);
	if (f.is_open()) {

		streampos size = f.tellg();
		for (int var = 1; var <= size; var++) {
			f.seekg(-var, ios::end);
			f.get(x);

			if (x == 0) {
				continue;
			}
			//windows注意跳过\r
			if (x == '\n') {
				string templine = line;
				if (templine.size() > 0) {
                    //这就是完整的一行了:templine
					lines.push_back(templine);
				}
				line = "";
			}
			else {
				line = x + line;
			}

			x = 0;
		}
		if (line.size() > 0) {
			lines.push_back(line);
		}


		f.close();
	}

	cout << lines.size() << endl;


	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值