代码之家  ›  专栏  ›  技术社区  ›  Surya Narayanan

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

  •  2
  • Surya Narayanan  · 技术社区  · 11 年前

    我正在实现一个低重量的应用程序,我必须经常打开并读取/proc/pid或tid/task/stat的详细信息。如果应用程序是多线程的,我必须读取更多的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;
    }
    
    2 回复  |  直到 10 年前
        1
  •  2
  •   Klas Lindbäck    11 年前

    试试这样的方法:

    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 以监视多个文件中的新数据(您需要保持它们的打开状态)。

        2
  •  1
  •   Shiva    11 年前

    尝试一下 rewind() 不要关闭你的文件。

    完成读取操作后,关闭那里的文件。