c - 从正在用 C 修改的文件中读取

标签 c unix

我有一个程序正在将结果写入文件,我想从该文件中实时读取。它是一个普通的文本文件,外部程序总是写一整行。我只需要在 Linux 系统上运行它。

int last_read = 0;
int res;
FILE *file;
char *buf;
char *end = buf + MAXLINE - 1;
int c;
int fileSize;
char *dst;
while (external_programme_is_running()) {
   file = fopen(logfile, "r"); //without opening and closing it's not working
   fseek(file, 0, SEEK_END);
   fileSize = ftell(file);
   if (fileSize > last_read) {
      fseek(file, last_read, SEEK_SET);
      while (!feof(file)) {
        dst = buf;
        while ((c = fgetc(file)) != EOF && c != '\n' && dst < end)
            *dst++ = c;
        *dst = '\0';
        res = ((c == EOF && dst == buf) ? EOF : dst - buf);

         if (res != -1) {
            last_read = ftell(file);
            parse_result(buf)
         }
      }
  }
  fclose(file);
}

这是正确的做法吗?或者检查修改时间然后打开文件会更好吗?如果同时修改文件,是否可能导致读取崩溃?

最佳答案

为避免每次循环迭代都需要关闭、重新打开和重新查找,请在读取 EOF 后在流上调用 clearerr

关于c - 从正在用 C 修改的文件中读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12206802/

相关文章:

c - 在 C 中声明全局多维数组

c - 需要左值作为赋值的左操作数......?

c++ - 在 ANTLR 生成的 C 解析器中使用 C++ 类型

shell - 运行 unix 命令时出现 "ksh: no space"-错误

linux - 使用 PID 文件杀死守护进程

c - "recv"即使已接受连接也无法正常工作

ubuntu - vfork() child 拥有什么特权?

kill 命令后关闭文件

c - 使用管道进行进程间通信

c - AIX,子进程退出时父进程无法捕获 SIGCHLD