setbuf()、setvbuf() 或 fflush(),- 并捕获 SIGINT 或任何与您的系统相关的适当内容。
即
#include <stdio.h>
#include <unistd.h> /* for sleep() in this example */
int main(void)
{
FILE *fh;
char *fn = "main.log";
int i;
if ((fh = fopen(fn, "w")) == NULL) {
fprintf(stderr,
"Unable to open file %s\n", fn);
return 1;
}
setbuf(fh, NULL); /* Turns buffering completely off */
for (i = 1; ; ++i) {
fprintf(fh, "%d ok ", i);
if (!(i%120))
fprintf(fh, "\n");
sleep(1);
}
fclose(fh);
return 0;
}
在其他控制台中:
$ tail -f main.log
产量:
1 好 2 好 3 好 4 好 5 好 6 好 ^C
或者fflush(fh),当你想刷新写缓冲区时。
stdio.h:>
int setvbuf(FILE* stream, char* buf, int mode, size_t size);
控制流流的缓冲。模式是 _IOFBF 用于完全缓冲,_IOLBF 用于行缓冲,_IONBF 用于无缓冲。非空 buf 指定要使用的大小大小的缓冲区;否则,分配一个缓冲区。出错时返回非零值。 调用必须在流上的任何其他操作之前。
void setbuf(FILE* stream, char* buf);
控制流流的缓冲。对于null buf,关闭缓冲,否则等价于(void)setvbuf(stream, buf, _IOFBF, BUFSIZ)。
int fflush(FILE* stream);
刷新流并在成功时返回零或在错误时返回 EOF。输入流的效果未定义。 fflush(NULL) 刷新所有输出流。