C++实时处理不断被写入的文件

最近业务上需要实现一个解析远程终端输出结果的指令,通过ssh将远程服务器终端结果重定向 到本地,再解析终端输出,提取有用的信息做下一步的处理。由于终端会不停的输出,因此重定向的文件也会不断的更新。目前采用的机制是轮训的办法,记录已经读取的文件位置,不断获取当前文件的最新位置并更新读取位置。具体代码如下

#include<iostream>
#include<fstream>
#include<string>
using namespace std;
static int last_position = 0;//记录当前已经处理掉的文件位置
void doSomething(string line)
{
    std::cout << "**** " << line  << " ****"<< std::endl;
}
void find_last_line(ifstream &infile)
{
    infile.seekg(0, ios::end);
    int filesize = infile.tellg();
    for(int n = last_position; n < filesize; n++)
    {
        infile.seekg(last_position, ios::beg);
        string line;
        getline(infile, line);
        doSomething(line);//获取最新行的内容
        if(infile.tellg()>0)//这里必须加入这个判断,因为在频繁更新目标文件时,会导致该函数返回-1
        {
            n = last_position = infile.tellg();
        }
    }
}
int main(int argc, char *argv[])
{
    if(argc !=2 )
    {
        cout << "请输入待处理的文件. e.g.: ./main file"<<endl;
        return -1;
    }
    int position = 0;
    while(true)
    {
        ifstream infile(argv[1]);
        find_last_line(infile);
    }
}

猜你喜欢

转载自blog.csdn.net/jxhaha/article/details/78499619