我正在实现一个低重量的应用程序,我必须经常打开并读取/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/