c - 使用C连续读取已打开的文件

标签 c file-io polling

我正在实现一个低重量的应用程序,我必须经常打开并读取/proc/pid 或 tid/task/stat 详细信息。如果应用程序是多线程的,我必须阅读更多统计文件。因此打开、读取和关闭使我的监控应用程序非常慢。有没有办法避免重复打开文件并且仍然能够读取更新的内容?

我进行了以下实验,但没有看到成功。我更改了“test.txt”中的数据,但未读取新数据。是不是因为内存中的文件没有更新?当我修改并保存“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;
}

最佳答案

尝试这样的事情:

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
}

您可以通过研究 source code for tail 找到完整的示例。上面的代码是对forward.c 的修改摘录。

您可以使用select来监视多个文件的新数据(您需要保持它们打开)。

关于c - 使用C连续读取已打开的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19538785/

相关文章:

c# - 在 C# Mono Debian 中读取文件不起作用

javascript - 使用 jQuery 和 AJAX 轮询服务器,没有初始延迟

cassandra - 如何在 cassandra 中进行轮询?

c++ - 通过 SWIG 在 python 中使用 std::ifstream、std::ofstream 的技术?

将特定数组元素转换为整数值

c - 循环二维数组中所有邻居对(2 点团)的高效算法

c - 关于sigsetjmp的一些错误

c - 用户输入.txt文件搜索C

angular - 动态改变轮询间隔

c - 如何处理具有运行时确定布局的 C 结构?