tail日志跟踪功能实现

来源:互联网 发布:模拟数据库建立 统计 编辑:程序博客网 时间:2024/05/21 19:30

最近工作中经常要看服务进程打印的日志,对实时打印的日志进行查看,于是想到了tail -f这个linux中常用的方式,因为是在windows中,就使用了mingw里面的tail凑合用,但因后来升级win10,系统崩了,重装之后也懒得再装什么mingw什么的,就观察了一下tail -f的行为,发现编辑后的文件如果是在中间插入,则在中间加了几个就会把最后的几个字节打印出来比如原来是abcdef,显示为abcdef,编辑后变成ab123cdef,显示就变成了abcdefdef,大体就知道了这玩意儿是怎么弄的了,应该是每次记录一下文件结尾,在用类似于fseek之类的重新定位后输出。(csdn的排版太乱了,也不会排,凑合看吧),功能十分原始,只实现了跟踪功能,代码糟糕,瞎眼勿喷。

代码如下:

#include <iostream>
#include <fstream>
#include <windows.h>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
if(argc <2)
{
cerr<<"请输入文件路径"<<endl;
return -1;
}
char * fname = argv[1];
ifstream fin = ifstream(fname,std::ios_base::in);
if(fin == NULL){
return 0;
}
long curp=0;//当前监听文本流结尾
long lastp=0;//读取至哪里
char t;
while(1){
while(1){
fin.read(&t,1);
if(fin.eof()){
break;
}
cout<<t;
lastp = curp = fin.tellg();
}
while(1){
fin.close();

Sleep(250);
fin.open(fname,std::ios_base::in);
fin.seekg(0,ios::end);


curp = fin.tellg();
if(curp > lastp){
fin.seekg(lastp,ios::beg);
break;
}
else if(curp < lastp){
fin.seekg(0,ios::beg);
cout<<endl<<"注意:文件可能被截断"<<endl;
break;
}

}
}
return 0;
}

0 0
原创粉丝点击