我有一个程序正在将结果写入文件,我想从该文件中实时读取。它是一个普通的文本文件,外部程序总是写一整行。我只需要在 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/