谈谈如何通过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;
}

 

另外提供一个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;
}

 

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值