通常我们很多场合都需要用到如何读增量的文件,其实应用领域还是蛮多的。日志读取。数据同步等应用场合。都是可以用上的。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#define FILE_LINE_LEN 1024
long g_curr_offset = 0;
int32_t c_tail(const char *file);
int32_t c_tail(const char *file)
{
if (!file) return -1;
FILE *fp = fopen(file, "r");
if (!fp) {
printf("cant open file, file: %s\n", file);
return -2;
}
fseek(fp, g_curr_offset, SEEK_SET);
char text[FILE_LINE_LEN];
uint32_t len;
while(!feof(fp)) {
memset(text, 0x0, FILE_LINE_LEN);
fgets(text, FILE_LINE_LEN, fp);
len = strlen(text);
if (len == 0 || text[len - 1] != '\n') continue;
text[len - 1] = 0;
g_curr_offset += len;
printf("%s\n", text);
}
fclose(fp);
return 0;
}
int main(int argc, char *argv[])
{
if (argc != 2) {
printf("Usage: exe file_name\n");
exit(-1);
}
while (1) {
c_tail(argv[1]);
}
return 0;
}
另外提供一个c++的写法
#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);
usleep(1000*15);
continue;
}
getline(ifs, row);
cout<<row<<endl;
seek = ifs.tellg();
}while(1);
ifs.close();
return 0;
}