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()

Follow us on Facebook and Twitter for latest update.

C Programming: Tips of the Day

Reading a string with scanf :

An array "decays" into a pointer to its first element, so scanf("%s", string) is equivalent to scanf("%s", &string[0]). On the other hand, scanf("%s", &string) passes a pointer-to-char[256], but it points to the same place.

Then scanf, when processing the tail of its argument list, will try to pull out a char *. That's the Right Thing when you've passed in string or &string[0], but when you've passed in &string you're depending on something that the language standard doesn't guarantee, namely that the pointers &string and &string[0] -- pointers to objects of different types and sizes that start at the same place -- are represented the same way.

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