c++ 实现“实时”读取不断有增量写入的文本文件

本文展示了如何使用C++实现一个程序,该程序能够实时读取一个持续有增量内容写入的文本文件。程序会检查文件末尾,如果超过指定时间戳(如60秒)仍未发现新内容,程序将自动退出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

      啥也别说,先上代码

/*
 * File:   readuntil.cpp
 * Author: @肖武 <tsxw24@gmail.com>
 *
 * Created on 2013年8月30日, 上午10:44
 */
#include <iostream>
#include <fstream>
#include <string>
#include <unistd.h>
#include <ctime>
#include <cstdlib>

using namespace std;

int main(int argc, char* argv[]) {
	if (argc != 3){
		cout<<argv[0]<<" [in_file] [max_time]"<<endl;
		return 1;
	}

	time_t max_time = atol(argv[2]);


	ifstream ifs;
	ifs.open(argv[1], ios::in);
	if (!ifs) {
		cout<<"open erro"<<endl;
		return 1;
	}

	string row;
	size_t seek;
	time_t t;
	do{
		if (ifs.peek() == EOF) {
			time(&t);
			if (t>max_time){
				break;
			}
			ifs.clear();
			ifs.seekg(seek, ios::beg);
			sleep(3);
			continue;
		}

		getline(ifs, row);
		cout<<row<<endl;
		seek = ifs.tellg();
	}while(1);
	ifs.close();

	return 0;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值