控制流缓冲。Controls stream buffering. 此函数已弃用;请改用 setvbufThis function is deprecated; use setvbuf instead.


void setbuf(
   FILE *stream,
   char *buffer


指向文件结构的指针。Pointer to FILE structure.

用户分配的缓冲区。User-allocated buffer.


Setbuf函数控制对流的缓冲。The setbuf function controls buffering for stream. 参数必须引用未读取或写入的打开文件。The stream argument must refer to an open file that hasn't been read or written. 如果缓冲区参数为NULL,则流未缓冲。If the buffer argument is NULL, the stream is unbuffered. 如果不是,则缓冲区必须指向长度为BUFSIZ的字符数组,其中BUFSIZ是 stdio.h 中定义的缓冲区大小。高.If not, the buffer must point to a character array of length BUFSIZ, where BUFSIZ is the buffer size as defined in STDIO.H. 用户指定的缓冲区(而不是给定流的默认系统分配的缓冲区)用于 I/O 缓存。The user-specified buffer, instead of the default system-allocated buffer for the given stream, is used for I/O buffering. 默认情况下, stderr流是无缓冲的,但您可以使用setbufstderr分配缓冲区。The stderr stream is unbuffered by default, but you can use setbuf to assign buffers to stderr.

setbuf已替换为setvbuf,这是新代码的首选例程。setbuf has been replaced by setvbuf, which is the preferred routine for new code. setvbuf不同, setbuf无法报告错误。Unlike setvbuf, setbuf has no way of reporting errors. setvbuf还允许同时控制缓冲模式和缓冲区大小。setvbuf also lets you control both the buffering mode and the buffer size. 存在setbuf ,以便与现有代码兼容。setbuf exists for compatibility with existing code.


例程所返回的值Routine 必需的标头Required header
setbufsetbuf <stdio.h><stdio.h>

有关其他兼容性信息,请参阅 兼容性For additional compatibility information, see Compatibility.


// crt_setbuf.c
// compile with: /W3
// This program first opens files named DATA1 and
// DATA2. Then it uses setbuf to give DATA1 a user-assigned
// buffer and to change DATA2 so that it has no buffer.

#include <stdio.h>

int main( void )
   char buf[BUFSIZ];
   FILE *stream1, *stream2;

   fopen_s( &stream1, "data1", "a" );
   fopen_s( &stream2, "data2", "w" );

   if( (stream1 != NULL) && (stream2 != NULL) )
      // "stream1" uses user-assigned buffer:
      setbuf( stream1, buf ); // C4996
      // Note: setbuf is deprecated; consider using setvbuf instead
      printf( "stream1 set to user-defined buffer at: %Fp\n", buf );

      // "stream2" is unbuffered
      setbuf( stream2, NULL ); // C4996
      printf( "stream2 buffering disabled\n" );
stream1 set to user-defined buffer at: 0012FCDC
stream2 buffering disabled

请参阅See also

流 I/OStream I/O
fclose、_fcloseallfclose, _fcloseall
fopen、_wfopen_wfopenfopen, _wfopen