最近由于项目需要,需要对文件中实时新增的数据进行处理,结合tail -f的逻辑,用c语言实现了这一功能,代码如下:
- #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;
- }
这段代码的核心就是每次在读取文件时,记录下文件被读取的总字节数,然后下次读取时,跳过已经读取的字节数,从新增的地方开始读取。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)