C参考手册
文件输入/输出 | File input/output
setbuf
在头文件<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函数