##### cppreference.com

##### Search

Create account

##### Namespaces

- Page
- Discussion

##### Variants

##### Views

- View
- Edit
- History

##### Actions

# setvbuf

From cppreference.com
< c‎ | io

Defined in header `<stdio.h>` |  |

int setvbuf( FILE * stream, char * buffer, int mode, size_t size ); |  | (until C99)
int setvbuf( FILE *restrict stream, char *restrict buffer, int mode, size_t size ); |  | (since C99)

Sets the internal buffer of the given file stream `stream`.

### [edit] Parameters

stream | - | the file stream to set the buffer to
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
size | - | size of the buffer

### [edit] Return value

​0​ on success or nonzero on failure.

### [edit] Notes

This function may only be used after `stream` has been associated with an open file, but before any other operation.

`buffer` may be null, in which case this call only resizes the internal buffer.

### [edit] Example

setvbuf with error checking

Run this code

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

    int main(void)
    {
        int file_size;
        char buffer[BUFSIZ];
        FILE * fp = fopen("test.txt","w+");
        if (setvbuf(fp,buffer,_IOFBF,BUFSIZ) != 0)
        {
           perror("setvbuf()");
           fprintf(stderr,"setvbuf() failed in file %s at line # %d\n", __FILE__,__LINE__-3);
           exit(EXIT_FAILURE);
        }

        /* Exhibit the contents of buffer. */
        fputs ("aaa",fp);
        printf("%s\n", buffer);
        fputs ("bbb",fp);
        printf("%s\n", buffer);
        fputs ("ccc",fp);
        printf("%s\n", buffer);
        file_size = ftell(fp);
        printf("file_size = %d\n", file_size);
        fflush (fp);              /* flush buffer */
        printf("%s\n", buffer);
        fputs ("ddd",fp);
        printf("%s\n", buffer);
        fputs ("eee",fp);
        printf("%s\n", buffer);

        rewind(fp);               /* flush buffer and rewind file */
        char buf[20];
        fgets(buf,sizeof buf,fp);
        printf("%s\n", buf);

        fclose(fp);

        return 0;
    }

Output:

    aaa
    aaabbb
    aaabbbccc
    file_size = 9
    aaabbbccc
    dddbbbccc
    dddeeeccc
    aaabbbcccdddeee

### [edit] See also

setbuf | sets the buffer for a file stream (function) [edit]
C++ documentation for setvbuf

Retrieved from "http://en.cppreference.com/mwiki/index.php?title=c/io/setvbuf&oldid=69899"