下面是使用 fflush() 的示例代码:
#include <string.h>
#include <stdio.h>
#include <conio.h>
#include <io.h>
void flush(FILE *stream);
int main(void)
{
FILE *stream;
char msg[] = "This is a test";
/* create a file */
stream = fopen("DUMMY.FIL", "w");
/* write some data to the file */
fwrite(msg, strlen(msg), 1, stream);
clrscr();
printf("Press any key to flush DUMMY.FIL:");
getch();
/* flush the data to DUMMY.FIL without closing it */
flush(stream);
printf("\nFile was flushed, Press any key to quit:");
getch();
return 0;
}
void flush(FILE *stream)
{
int duphandle;
/* flush the stream's internal buffer */
fflush(stream);
/* make a duplicate file handle */
duphandle = dup(fileno(stream));
/* close the duplicate handle to flush the DOS buffer */
close(duphandle);
}
我知道的关于fflush()的一切就只有它是一个库函数用来刷新输出缓冲区。我想知道使用fflush()的基本目的在哪里,我可以在哪里使用它。最主要的是,我想知道使用fflush()会有什么问题。
printf()
而没有任何换行符时,它可能不会立即打印。如果您知道您的程序可能随时崩溃,您可以使用fflush()
(或换行符...)。我认为这不是常见用法。 - Elazarfflush()
。 - thejhstdio
的整个目的是为read()
和write()
系统调用提供应用程序端的缓冲。任何时候使用缓冲都需要刷新操作。唯一可识别的问题是在需要时忘记使用它,或者可能过度使用它,例如在循环内部而不是在循环结束时使用。 - user207421