C setbuf() function

C library function - setbuf()

The setbuf() function controls buffering for the specified stream if the operating system supports user-defined buffers. The stream pointer must refer to an open file before any I/O or repositioning has been done.


void setbuf(FILE *stream, char *buffer)

setbuf() Parameters:

Name Description Required /Optional
stream Identifies an address for a file descriptor, which is an area of memory associated with an input or output stream. Required
buffer The system uses the buffer, which you specify, for input/output buffering instead of the default system-allocated buffer for the given stream. Required

Return value from setbuf()

  • This function does not return any value.

Example: setbuf() function

The following example opens the file test.txt for writing. As a result, it calls the setbuf() function in order to create a buffer of length BUFSIZ. Strings are written to the stream using the buffer buf, which contains the string before it is flushed to the file.

#include <stdio.h>
#include <string.h>
int main(void)
   char buf[BUFSIZ];
   char string[] = "C Programming.";
   FILE *stream;
   memset(buf,'\0',BUFSIZ);  /* initialize buf to null characters */
   stream = fopen("test.txt", "wb");
   setbuf(stream,buf);       /* set up buffer */
   fwrite(string, sizeof(string), 1, stream);
   printf("String is found in buffer now. %s\n",buf);       /* string is found in buf now */
   fclose(stream);           /* buffer is flushed out to myfile.dat */


String is found in buffer now. C Programming.

C Programming Code Editor:

Previous C Programming: C rewind()
Next C Programming: C setvbuf()

Share this Tutorial / Exercise on : Facebook and Twitter

C Programming: Tips of the Day

What's an object file in C?

An object file is the real output from the compilation phase. It's mostly machine code, but has info that allows a linker to see what symbols are in it as well as symbols it requires in order to work. (For reference, "symbols" are basically names of global objects, functions, etc.)

A linker takes all these object files and combines them to form one executable (assuming that it can, i.e.: that there aren't any duplicate or undefined symbols). A lot of compilers will do this for you (read: they run the linker on their own) if you don't tell them to "just compile" using command-line options. (-c is a common "just compile; don't link" option.)

Ref : https://bit.ly/3CbzF8M