linux下c语言实现tail -f功能---实时读取变化文件中的增量内容
2016-12-24 21:19
1181 查看
最近由于项目需要,需要对文件中实时新增的数据进行处理,结合tail -f的逻辑,用c语言实现了这一功能,代码如下:
[cpp] view
plain copy
#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;
}
这段代码的核心就是每次在读取文件时,记录下文件被读取的总字节数,然后下次读取时,跳过已经读取的字节数,从新增的地方开始读取。
[cpp] view
plain copy
#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;
}
这段代码的核心就是每次在读取文件时,记录下文件被读取的总字节数,然后下次读取时,跳过已经读取的字节数,从新增的地方开始读取。
相关文章推荐
- linux下c语言实现tail -f功能---实时读取变化文件中的增量内容
- 纯JS实现的读取excel文件内容功能示例【支持所有浏览器】
- EditText+RecycleView实现搜索功能之一:对EditText内容变化实时监听
- rsync+sersync 实现实时同步有变化文件功能 安装配置
- 使用文件操作函数实现简单的CP、cat、size功能及读取文件内容初始化结构体
- c/c++: 读取配置文件(文本)内容的简单实现
- C语言实现的配置文件读取功能,喜欢的拿去用.
- 读取txt文件实现搜索替换功能
- c++ 实现“实时”读取不断有增量写入的文本文件
- Python实现txt文件内容快速合并功能
- 读取Spring配置文件 main方法里面测试实现功能
- php读取csv实现csv文件下载功能
- 使用FileInputStream类, 实现从磁盘读取本应用程序源代码文件,并将文件内容显示在屏幕上。
- 尝试用android-logging-log4j去实现log输出内容到sd卡中的文件的功能
- IE下使用控件实现读取本地文件功能并显示
- PHP读取网页文件内容的实现代码(fopen,curl等)
- python计算文件的行数和读取某一行内容的实现方法
- Hpple-iOS解析HTML-hpple读取html文件内容的代码 更新了下拉刷新功能
- 读取文件的每一行内容并输出 的shell脚本实现
- Linux下实时跟踪log4j日志文件的bash脚本 - 增强了tail -f的功能