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)
C语言中清除内存缓冲区的函数是fflush(),清除输入缓冲区用fflush(stdin)
其中stdin表示标准输入。
该函数通常用在输入类函数的前面,用以清除输入缓冲区中的内容,避免接收到上次残留的内容而出错。
举例如下:
1、不加fflush函数:
// 将输入的5个字符存放到数组str中,并输出
int i
char ch, str[6]={'\0'}
for(i=0i<5i++)
{
scanf("%c", &ch)
str[i] = ch
}
printf("%s\n", str)
// 程序只能输入三个字符(每个字符间包含一个回车符),因为不加fflush函数时,将残留在缓冲区中的回车符也当成了一个字符输入到数组str中。
2、加fflush函数:
int i
char ch, str[6]={'\0'}
for(i=0i<5i++)
{
fflush(stdin) // 清除留在缓冲区中的回车符,确保接收到的是用户输入的字符
scanf("%c", &ch)
str[i] = ch
}
printf("%s\n", str)
// 程序能正常输出