您的位置:首页 > 编程语言 > C语言/C++

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

2013-09-25 14:36 1961 查看
啥也别说,先上代码

/*
* 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;
}


编译

$ g++ readuntil.cpp


参数说明

$ ./a.out
./a.out [in_file] [max_time]

in_file 是要读取文件路径

max_time 是时间戳,若大于此时间,并且读到文件末尾,则退出程序

测试,读取f.log, 60秒后若读到文件结尾,则退出

$ ./a.out f.log $[`date '+%s'`+60]
123
adsf
adsf
sadddd
sddsd
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: