setbuf

在写输入的时候遇到一个问题,我们可能会不小心多输入了数据,这样就会影响到我们接下来的输入输出结果,怎么来消除缓冲区中多余的数据?

setbuf函数可以实现setbuf(stdin,NULL)清空缓冲区内容。

具体的setbuf用法如下:

void setbuf(FILE *stream,char *buffer);

 

  
  
  
  
  1. #include <stdio.h> 
  2.  
  3. int main( void )  
  4. {  
  5.    char buf[BUFSIZ];  
  6.    FILE *stream1, *stream2;  
  7.  
  8.    fopen_s( &stream1, "data1", "a" );  
  9.    fopen_s( &stream2, "data2", "w" );  
  10.  
  11.    if( (stream1 != NULL) && (stream2 != NULL) )  
  12.    {  
  13.       // "stream1" uses user-assigned buffer:  
  14.       setbuf( stream1, buf ); // C4996  
  15.       // Note: setbuf is deprecated; consider using setvbuf instead  
  16.       printf( "stream1 set to user-defined buffer at: %Fp\n", buf );  
  17.  
  18.       // "stream2" is unbuffered  
  19.       setbuf( stream2, NULL ); // C4996  
  20.       printf( "stream2 buffering disabled\n" );  
  21.       _fcloseall();  
  22.    }  
  23. }  
  24. stream1 set to user-defined buffer at: 0012FCDC  
  25. stream2 buffering disabled 

The setbuf function controls buffering for stream. The stream argument must refer to an open file that has not been read or written. If the buffer argument isNULL, the stream is un-buffered. If not, the buffer must point to a character array of length BUFSIZ, where BUFSIZ is the buffer size as defined in STDIO.H. The user-specified buffer, instead of the default system-allocated buffer for the given stream, is used for I/O buffering. The stderr stream is un-buffered by default, but you can use setbuf to assign buffers to stderr.

你可能感兴趣的:(缓冲区)