如何从另一个程序c ++ linux经常附加的文件中读取

时间:2016-03-29 19:36:43

标签: c++ file io

所以我有一个写入文件的进程。我正在创建的新进程将打开此文件,理想情况下会读取对其进行的任何更改并对其进行处理。

到目前为止控制这个的类我打开文件

稍后在另一个函数中,我不断地读取它以检查更改并处理它们

它模糊地看起来像

open(file);
while(1)
{
fread(buffer, 1, 16000, file);
//do something 
}

问题是,我一直在调试它,让它拉入一个空文件,然后在打开后写入它。 FILE对象永远不会看到任何更改。

我是否需要关闭eof并重新打开?顶部是为了使更改起作用?

2 个答案:

答案 0 :(得分:1)

您可以使用ftell跳转到文件的末尾,然后int current = 0, last = 0; FILE *f=fopen(filename, "r"); if (!f) { perror("can't open file"); exit(1); } while (1) { fseek(f, 0, SEEK_END); current = ftell(f); if (current != last) { printf("len=%d\n",current); fseek(f, current, SEEK_SET); last = current; fread(buffer, 1, 16000, f); .... } usleep(100); } 查看您的偏移量。如果它从上次更改,您知道有更多数据。

formData.entries()

答案 1 :(得分:0)

dbush建议的替代方法:

/* declare buffer, file and open file */
size_t rc;
while (1) {
   if ((rc = fread(buffer, 1, 16000, file)) == 0) {
       if (feof(file))            {
           clearerr(file);
           usleep(100);
       }  else {
           /* it's a real error, not EOF */
       }
   } else {
       /* process rc bytes in buffer */
   }
}