首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

std::setvbuf

Defined in header <cstdio>

?

?

int setvbuf( std::FILE* stream, char* buffer, int mode, std::size_t size );

?

?

更改给定文件流的缓冲模式。stream如论点所示mode.此外,

  • 如果buffer为空指针,则内部缓冲区调整大小为size...
  • 如果buffer不是空指针,则指示流使用用户提供的大小缓冲区。size开始于buffer。流必须关闭%28与fclose%29在寿命所指向的数组的buffer结束了。调用成功后的数组的内容。setvbuf是不确定的,任何使用它的尝试都是未定义的行为。

参数

stream

-

the file stream to set the buffer to or null pointer to change size and mode only

buffer

-

pointer to a buffer for the stream to use

mode

-

buffering mode to use. It can be one of the following values: _IOFBF full buffering _IOLBF line buffering _IONBF no buffering

_IOFBF

full buffering

_IOLBF

line buffering

_IONBF

no buffering

_IOFBF

full buffering

_IOLBF

line buffering

_IONBF

no buffering

size

-

size of the buffer

返回值

?0?关于成功还是失败。

注记

此函数只能在stream已与打开的文件相关联,但在任何其他操作%28之前(除失败的调用之外)std::setbuf/std::setvbuf29%。

不是全部size字节必然用于缓冲:实际缓冲区大小通常被舍入为2的倍数、页面大小的倍数等。

在许多实现中,行缓冲仅适用于终端输入流。

一个常见错误是将stdin或stdout缓冲区设置为一个数组,该数组的生存期在程序终止之前结束:

二次

代码语言:javascript
复制
int main() {
    char buf[BUFSIZ];
    std::setbuf(stdin, buf);
} // lifetime of buf ends, undefined behavior

二次

默认缓冲区大小BUFSIZ对于文件I/O的实现来说,预计是最有效的缓冲区大小,但是POSIX。fstat经常提供更好的估计。

改变缓冲区大小的一个用例是当知道更好的大小时。

二次

代码语言:javascript
复制
#include <iostream>
#include <cstdio>
#include <stdlib.h>
#include <sys/stat.h>
 
int main()
{
    std::FILE* fp = std::fopen("test.txt", "r");
    if(!fp) {
       std::perror("fopen"); return 1;
    }
 
    struct stat stats;
    if(fstat(fileno(fp), &stats) == -1) { // POSIX only
        std::perror("fstat"); return 1;
    }
 
    std::cout << "BUFSIZ is " << BUFSIZ << ", but optimal block size is "
              << stats.st_blksize << '\n';
    if(std::setvbuf(fp, NULL, _IOFBF, stats.st_blksize) != 0) {
       perror("setvbuf failed"); // POSIX version sets errno
       return 1;
    }
 
    int ch;
    while((ch=std::fgetc(fp)) != EOF); // read entire file: use truss/strace to
                                       // observe the read(2) syscalls used
    std::fclose(fp);
}

二次

可能的产出:

二次

代码语言:javascript
复制
BUFSIZ is 8192, but optimal block size is 65536

二次

另见

setbuf

sets the buffer for a file stream (function)

setbuf virtual

provides user-supplied buffer or turns this filebuf unbuffered (virtual protected member function of std::basic_filebuf)

c setvbuf的文档

代码语言:txt
复制
 ? cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com