罗卓英与叶挺将军:C语言fflush(stdin)函数是什么意思,在什么情况下用它

来源:百度文库 编辑:高考问答 时间:2024/05/02 02:38:12
我在有些C程序中见到fflush(stdin),不知道它是干什么用的,请问在什么情况下用它?另外,本人的联想能力也挺丰富的,本人想既然有fflush(stdin),那是否也有fflush(stdout)?如果有,它又是干什么用的?

1.fflush函数包含在stdio.h头文件中,用来强制将缓冲区中的内容写入文件。
2.函数原型:int fflush(FILE *stream) ;
3.函数功能:清除一个流,即清除文件缓冲区,当文件以写方式打开时,将缓冲区内容写入文件。也就是说,对于ANSI C规定的是缓冲文件系统,函数fflush用于将缓冲区的内容输出到文件中去。
4.函数返回值:如果成功刷新,fflush返回0。指定的流没有缓冲区或者只读打开时也返回0值。返回EOF指出一个错误。
5.下面给出一个具体的例子来演示该函数使用的方法:
#include <stdio.h>
#include <stdlib.h>
int main(void){
FILE *fp;
if((fp=fopen("test", "rb"))==NULL) {
printf("Cannot open file.\n");
exit(1);
}
char ch = 'C';
int i;
for(i=0; i<5; i++) {
fwrite(ch, sizeof(ch), 1, fp);
fflush(fp);
}
fclose(fp);
return 0;
}
注意:如果在写完文件后调用函数fclose关闭该文件,同样可以达到将缓冲区的内容写到文件中的目的,但是那样系统开销较大。

清除文件缓冲区,文件以写方式打开时将缓冲区内容写入文件

没有你后面说的那个。

例子:
#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";
stream = fopen("DUMMY.FIL", "w");
fwrite(msg, strlen(msg), 1, stream);
clrscr();
printf("Press any key to flush DUMMY.FIL:");
getch();
flush(stream);
printf("
File was flushed, Press any key to quit:");
getch();
return 0;
}
void flush(FILE *stream)
{
int duphandle;
fflush(stream);
duphandle = dup(fileno(stream));
close(duphandle);
}

fflush(stdin)刷新标准输入缓冲区,把输入缓冲区里的东西丢弃
fflush(stdout)刷新标注输出缓冲区,把输出缓冲区里的东西打印到标准输出设备上