Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

setvbuf — configure stream buffering

setvbuf selects an open stream's buffering mode before other operations and allows a caller-supplied buffer.

Version: C23; repository compiler flag, production runtime not attested

Syntax

#include <stdio.h>
int setvbuf(FILE * restrict stream, char * restrict buf, int mode, size_t size);

Call setvbuf from <stdio.h> after opening the stream, before any other operation on it; an unsuccessful setvbuf call is the exception.

mode: _IOFBF — full buffering, _IOLBF — line buffering, _IONBF — no buffering. Return value 0 means success; nonzero means an invalid mode or an unfulfilled request.

For buf != NULL, size specifies the array size; the library may use that array. Keep it alive until stream closure; its contents are unspecified. For buf == NULL, the library may use size when allocating a buffer.

The example closes stream before local buffer expires. Leaving the block without closing the stream would cause undefined behavior.

Examples

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    char buffer[BUFSIZ];
    FILE *stream = tmpfile();
    if (stream == NULL)
        return EXIT_FAILURE;

    if (setvbuf(stream, buffer, _IOFBF, sizeof buffer) != 0) {
        fclose(stream);
        return EXIT_FAILURE;
    }

    int failed = fputs("Hello\n", stream) == EOF;
    if (fclose(stream) == EOF)
        failed = 1;
    if (failed)
        return EXIT_FAILURE;

    return puts("OK") == EOF ? EXIT_FAILURE : EXIT_SUCCESS;
}

Result

OK

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources