w3resource

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.

Syntax:

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 */
}

Output:

String is found in buffer now. C Programming.

C Programming Code Editor:

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



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/c-programming/stdio/c_library_method_setbuf.php