C语言fflush(stdin)函数是什么意思,在什么情况下用它

Python011

C语言fflush(stdin)函数是什么意思,在什么情况下用它,第1张

1、fflush(stdin)是清空输入缓冲区的意思。stdin就是标准输入 std即standard(标准),in即input(输入),合起来就是标准输入。 一般就是指键盘输入到缓冲区里的东西。

2、在清除文件缓冲区时使用,文件以写方式打开时将缓冲区内容写入文件。

例:

#include <conio.h>

#include <io.h>

#include <stdio.h>

#include <string.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的注意事项

1、MSDN 文档里也清楚地写着:fflush on input stream is an extension to the C standard (fflush 操作输入流是对C标准的扩充)。以下是 C99 对 fflush 函数的定义:int fflush(FILE *stream)

2、如果stream指向输出流或者更新流(update stream),并且这个更新流最近执行的操作不是输入,那么fflush函数将把任何未被写入的数据写入stream指向的文件(如标准输出文件stdout)。

3、fflush函数的行为是不确定的。fflush(NULL)清空所有输出流和上面提到的更新流。如果发生写错误,flush函数会给那些流打上错误标记,并且返回EOF,否则返回0。

4、如果 stream 指向输入流(如 stdin),那么 fflush 函数的行为是不确定的。故而使用 fflush(stdin) 是不正确的。

参考资料来源:百度百科—fflush(stdin)

fflush()是标准I/O函数中的一个,从其字面意思也可以看出来是冲洗,刷新的意思。大家知道,在程序中进行读写操作的时候,一般情况下都要进行缓冲的,也就是将要读写的内容先保存到一块内存区域,这块内存区域就叫做“缓冲区”,然后在对这个缓冲区进行操作,一匹配不同的设备的读写速率不同的问题。所以很多时候,读写并不是立马就有效的,因为读写的内容被缓冲了。所以,在你想要立马显现效果的时候,可以对缓冲区的内容进行主动刷新,调用ffluash()函数,就是这个功能。此函数可以将缓冲区内任何没有写的数据发送到由一个文件指针指定的输出文件中去,这个过程也叫做刷新缓冲区。

fflush(stdin)中stdin是标准输入的意思。

fflush(stdin)的作用是清空标准输入缓冲区。

举例说明如下:

int a

char c

scanf("%d",&a)

fflush(stdin) // 清空输入缓冲区

scanf("%c",&c)如果不加fflush(stdin)的话,第一次输入的回车可能会被第二次输入操作所捕捉,也即变量c的值将会是回车符,并不会接收用户输入的字符。