C programming setbuf stdio.h


In C programming the <stdio.h> setbuf function allows the programmer to set a buffer size to BUFSIZ and the mode to _IOFBF;what does _IOFBF mean is discuss below.The declaration of the function is given below.

void setbuf(FILE * restrict stream , char * restrict buf);

Parameters:
stream -The file stream.

buf -A pointer pointing to the buffer.

Return type
void

As stated earlier the mode of the stream set by setbuf() is _IOFBF type.The _IOFBF will set the buffer to be fully buffer,this means only when the buffer is full the data are written to the file.For more information on various buffer type visit the link below.

Link :C what are stream and buffer?

***Note you may only call the setbuf() only after the file has been successfully opened,and before any file input output operations have taken place.

Link : C fopen stdio.h

Code example

/*Checking the size of BUFSIZ */
printf(“BUFSIZ=%i\n” , BUFSIZ);

FILE *fp=fopen(“text.txt” , “w” );

char *buf=(char*)malloc(BUFSIZ) ;

if( fp!=NULL )
{
setbuf( fp , buf); //The memory pointed by the ‘buf’ pointer is taken as the buffer for the file pointed by the ‘fp’ stream

fputs( “New buffer text” , fp); //printing text to text.txt file
}
else
  printf(“File opening fail”);

rewind( fp ); //Calling it is necessary before reading the content

/*Reading the content of the text.txt file */
int i=0 ;

while( (i=fgetc(fp))!=EOF )
{
putchar( i );
}

fclose( fp ); //do not forget!!!

Output,

BUFSIZ=512
New buffer text

In this program the only purpose of setbuf() it to set the size of the buffer to BUFSIZ,now only when the data in the buffer reaches to BUZSIZ characters the data is written to the file.

Link :C fclose stdio.h





Some points to note

If the second argument is a null pointer

If the second argument passed to the setbuf() function is a null pointer then the mode of the stream is set to _IONBF.The mode cause the input ans output to be unbuffered.

Code example

/*Checking the size of BUFSIZ */

FILE *fp=fopen(“text.txt” , “w” );

char *buf=NULL ;

if( fp!=NULL )
{
setbuf( fp , buf); //the input and output is unbuffer

/*Edit the file .. or do whatever you want with the file */
}
else
printf(“File opening fail”);

fclose( fp );


setbuf and setvbuf are similar

The function setbuf() and setvbuf() are similar.The only difference is in setbuf() the mode is fixed to _IOFBF or _IONBF;when the second argument is a null pointer.But in setvbuf() we can change the mode to any of the three modes _IOFBF , _IONBF and _IOLBF invariably.


Related links

->C setvbuf stdio.h

->C malloc stdlib.h