©
本文档使用
php中文网手册 发布
在头文件<stdio.h>中定义 | ||
|---|---|---|
void setbuf(FILE * stream,char * buffer); | (直到C99) | |
void setbuf(FILE * restrict stream,char * restrict buffer); | (自C99以来) |
设置内部缓冲区以用于流操作。它应该至少是BUFSIZ字符长。
如果buffer不为null,则相当于setvbuf(stream, buffer, _IOFBF, BUFSIZ)。
如果buffer为空,相当于setvbuf(stream, NULL, _IONBF, 0)关闭缓冲。
流 | - | 要设置缓冲区的文件流 |
|---|---|---|
缓冲 | - | 指向要使用的流的缓冲区。如果提供NULL,则关闭缓冲 |
没有。
如果BUFSIZ不是合适的缓冲区大小,setvbuf可以用来改变它。
setvbuf也应该用来检测错误,因为setbuf不表示成功或失败。
此功能可后方可使用stream已经以开放的文件相关联,但任何其他操作之前(除了一个失败的呼叫setbuf/ setvbuf)。
一个常见的错误是将stdin或stdout的缓冲区设置为在程序终止之前其生命周期结束的数组:
int main(void) {
char buf[BUFSIZ]; setbuf(stdin, buf);} // lifetime of buf ends, undefined behavior可以使用setbuf在需要立即输出的流上禁用缓冲。
#include <stdio.h>#include <threads.h>
int main(void){ setbuf(stdout, NULL); // unbuffered stdout putchar('a'); // 'a' appears immediately if stdout is unbuffered thrd_sleep(&(struct timespec){.tv_sec=1}, NULL); // sleep 1 sec putchar('b'); }输出:
ab
C11标准(ISO / IEC 9899:2011):
7.21.5.5 setbuf函数(p:307-308)
C99标准(ISO / IEC 9899:1999):
7.19.5.5 setbuf函数(p:273)
C89 / C90标准(ISO / IEC 9899:1990):
4.9.5.5 setbuf函数