gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 02:53:47 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com