阅读已经连续使用C打开的文件 [英] Reading already opened file continuously using C

查看:119
本文介绍了阅读已经连续使用C打开的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我实现低重量的应用程序在那里我有打开并经常阅读的/ proc / PID或TID /任务/ STAT细节。如果应用程序是多线程我要读更多的统计文件。所以打开,读取和关闭使我的监视应用程序很慢。是否有解决方案,以避免在打开文件多次,仍然能够读取更新的内容?

我跑了以下实验,但我没有看到成功。我更改了数据的test.txt,但新的数据不被读取。难道是因为文件没有在内存中更新?当我修改和保存的test.txt该怎么办?

 的#include<&stdio.h中GT;
诠释的main()
{
    FILE * PFILE;
    焦了mystring [100];
    PFILE = FOPEN(test.txt的,R);
    而(1){
        如果(PFILE == NULL)PERROR(错误打开文件);
        如果(与fgets(MyString的,100,PFILE)!= NULL){
            看跌期权(myString的);
            fseek的(PFILE,0,SEEK_SET);
        }
        睡眠(1);
    }
    FCLOSE(PFILE);
    返回0;
}


解决方案

尝试是这样的:

 为(;;){
    而((CH = GETC(FP))!= EOF){
        如果(的putchar(CH)== EOF)
            PERROR(输出错误);
    }
    如果(FERROR(FP)){
        的printf(输入错误:%s,错误号);
        返回;
    }
    (无效)fflush(标准输出);
    睡眠(1); //或者使用SELECT
}

您可以通过研究源$ C ​​$找到一个完整的示例下尾。在$ C $上面c是forward.c修改的节选。

您可以使用选择来监控新的数据几个文件(你需要保持通畅)。

I am implementing a low weight application where I have to open and read the /proc/pid or tid/task/stat details very often. If the application is multithreaded I have to read more stat files. So opening, reading and closing makes my monitoring application really slow. Is there a solution to avoid opening the file repeatedly and still able to read the updated content?

I ran the following experiment but I don't see success. I change the data in "test.txt" but the new data is not read. Is it because the file is not updated in memory? What happens when i modify and save "test.txt"?

#include <stdio.h>
int main()
{
    FILE * pFile;
    char mystring [100];
    pFile = fopen ("test.txt" , "r");
    while(1){
        if (pFile == NULL) perror ("Error opening file");
        if ( fgets (mystring , 100 , pFile) != NULL ){
            puts (mystring);
            fseek ( pFile , 0 , SEEK_SET );
        }
        sleep(1);
    }
    fclose (pFile);
    return 0;
}

解决方案

Try something like this:

for (;;) {
    while ((ch = getc(fp)) != EOF)  {
        if (putchar(ch) == EOF)
            perror("Output error");
    }
    if (ferror(fp)) {
        printf("Input error: %s", errno);
        return;
    }
    (void)fflush(stdout);
    sleep(1); // Or use select
}

You can find a full example by studying the source code for tail. The code above is a modified excerpt from forward.c.

You can use select to monitor several files for new data (you need to keep them open).

这篇关于阅读已经连续使用C打开的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆