linux下c语言实现tail -f功能---实时读取变化文件中的增量内容

本文介绍了一种使用C语言实现实时监控文件新增数据的方法。通过记录已读取的文件偏移量,在文件更新时仅读取新增内容,适用于日志文件等场景。

最近由于项目需要,需要对文件中实时新增的数据进行处理,结合tail -f的逻辑,用c语言实现了这一功能,代码如下:


[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. #include <string.h>  
  4. #include <stdint.h>  
  5.   
  6.   
  7. #define FILE_LINE_LEN 1024  
  8.   
  9. long g_curr_offset = 0;  
  10.   
  11. int32_t c_tail(const char *file);  
  12. int32_t c_tail(const char *file)  
  13. {  
  14.     if (!file) return -1;   
  15.     FILE *fp = fopen(file, "r");  
  16.     if (!fp) {  
  17.         printf("cant open file, file: %s\n", file);  
  18.         return -2;   
  19.     }     
  20.   
  21.     fseek(fp, g_curr_offset, SEEK_SET);  
  22.   
  23.     char text[FILE_LINE_LEN];  
  24.     uint32_t len;  
  25.     while(!feof(fp)) {  
  26.   
  27.         memset(text, 0x0, FILE_LINE_LEN);  
  28.         fgets(text, FILE_LINE_LEN, fp);  
  29.         len = strlen(text);  
  30.         if (len == 0 || text[len - 1] != '\n'continue;  
  31.         text[len - 1] = 0;  
  32.         g_curr_offset += len;  
  33.         printf("%s\n", text);  
  34.     }     
  35.   
  36.     fclose(fp);  
  37.   
  38.     return 0;  
  39. }  
  40. int main(int argc, char *argv[])  
  41. {  
  42.     if (argc != 2) {  
  43.         printf("Usage: exe file_name\n");  
  44.         exit(-1);  
  45.     }  
  46.   
  47.     while (1) {  
  48.         c_tail(argv[1]);  
  49.     }  
  50.   
  51.     return 0;  
  52. }  


这段代码的核心就是每次在读取文件时,记录下文件被读取的总字节数,然后下次读取时,跳过已经读取的字节数,从新增的地方开始读取。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值