关键词搜索

源码搜索 ×
×

fflush函数有什么作用?

发布2013-06-09浏览67448次

详情内容

      说明:

      有的朋友对本文的程序结果提出质疑,所以这里说一下,我是在Windows VC++6.0上测试的, 请注意平台和环境的不同。     

 

      先来复习一个简单单词吧:

      flush(注意只有一个f):冲洗,冲刷,冲掉。  

      例句:I flushed the toilet and went back to work again.

 

      下面,我们来看看一个简单的函数:fflush(file flush,注意有两个f), 先来看一个简单的程序:

 

  1. #include <stdio.h>
  2. int main()
  3. {
  4. char c;
  5. scanf("%c", &c);
  6. printf("%d\n", c);
  7. scanf("%c", &c);
  8. printf("%d\n", c);
  9. return 0;
  10. }

       运行这个程序,输入1, 并按enter键,结果为:

 

49
10
     

 

      不用吃惊,这个结果很正常的,字符1对应的ASCII值刚好为49, enter键对应的ASCII值为10, 所以就有这样的结果呢。可以看出,第二个scanf函数执行了,并从缓冲区中得到了值(其实,这个值不是我们想要的),那么我们如何把缓冲区这个“马桶”里面的值冲掉呢?用fflush函数就可以了。如下:

 

  1. #include <stdio.h>
  2. int main()
  3. {
  4. char c;
  5. scanf("%c", &c);
  6. printf("%d\n", c);
  7. fflush(stdin); // 冲掉“马桶”中的无用值
  8. scanf("%c", &c);
  9. printf("%d\n", c);
  10. return 0;
  11. }

      这样,就不会显示10了。

 

 

      下面,我们来看MSDN(2008)的一个例子(MSDN上给的程序当然是对的啊):

 

  1. #include <stdio.h>
  2. #include <conio.h>
  3. void main( void )
  4. {
  5. int integer;
  6. char string[81];
  7. /* Read each word as a string. */
  8. printf( "Enter a sentence of four words with scanf: " );
  9. for( integer = 0; integer < 4; integer++ )
  10. {
  11. scanf( "%s", string );
  12. printf( "%s\n", string );
  13. }
  14. /* You must flush the input buffer before using gets. */
  15. fflush( stdin );
  16. printf( "Enter the same sentence with gets: " );
  17. gets( string );
  18. printf( "%s\n", string );
  19. }

 

      要是不信那个邪,你把上面程序中的fflush那一行注释掉,运行一下程序,你就知道有什么后果了。

     从而,你也就懂了fflush的作用。


     最后,我们看看MSDN中一段话,以此结束本文:

 

fflush has no effect on an unbuffered stream.

Buffers are normally maintained by the operating system, which determines the optimal time to write the data automatically to disk: when a buffer is full, when a stream is closed, or when a program terminates normally without closing the stream. 

 

 

相关技术文章

点击QQ咨询
开通会员
返回顶部
×
微信扫码支付
微信扫码支付
确定支付下载
请使用微信描二维码支付
×

提示信息

×

选择支付方式

  • 微信支付
  • 支付宝付款
确定支付下载