setbuf

From cppreference.com
< c‎ | io

Defined in header <stdio.h>
void setbuf( FILE          *stream, char          *buffer );
(until C99)
void setbuf( FILE *restrict stream, char *restrict buffer );
(since C99)

Sets the internal buffer to use for stream operations. It should be at least BUFSIZ characters long.

If buffer is not null, equivalent to setvbuf(stream, buffer, _IOFBF, BUFSIZ)

If buffer is null, equivalent to setvbuf(stream, NULL, _IONBF, 0), which turns off buffering.

Contents

[edit] Parameters

stream - the file stream to set the buffer to
buffer - pointer to a buffer for the stream to use. If NULL is supplied, the buffering is turned off

[edit] Return value

None.

[edit] Example

#include <stdio.h>
 
int main(void)
{
    int file_size;
    char buffer[BUFSIZ];
    FILE * fp = fopen("test.txt","w+");
    setbuf(fp,buffer);
 
    /* 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

sets the buffer and its size for a file stream
(function)
C++ documentation for setbuf