📜  C++ setvbuf()

📅  最后修改于: 2020-09-25 08:34:57             🧑  作者: Mango

C++中的setvbuf() 函数用于更改或指定缓冲模式和缓冲区大小。

setvbuf()原型

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

setvbuf() 函数将给定文件流的缓冲模式更改为mode的值。

如果缓冲区不为null,则缓冲区的sizesize ,否则函数自动分配缓冲区(基于size值)。

它在头文件中定义。

setvbuf()参数

setvbuf()返回值

setvbuf() 函数成功返回零,失败返回非零。

示例:setvbuf() 函数的工作方式

#include 
#include 

#define SIZE 1024

using namespace std;

int main()
{
    char buffer[SIZE] = "...";
    char str[] = "This is first line\nThis is second line";
    FILE *fp = fopen("test.txt","wb+");

    /* no buffering, buffer remains unchanged */
    setvbuf(fp,buffer,_IONBF,SIZE);
    fwrite(str, sizeof(str), 1, fp);
    cout << buffer << endl;

    /* line buffering, only a single line is buffered */
    setvbuf(fp,buffer,_IOLBF,SIZE);
    fwrite(str, sizeof(str), 1, fp);
    cout << buffer << endl;

    /* full buffering, all the contents are buffered */
    setvbuf(fp,buffer,_IOFBF,SIZE);
    fwrite(str, sizeof(str), 1, fp);
    cout << buffer << endl;

    fclose(fp);
    return 0;
}

运行该程序时,输出为:

...
This is second line
This is first line
This is second line