C programming setvbuf stdio.h


In C programming the <stdio.h> setvbuf function allows the programmer to set a buffer size to the desirable size and the mode to any of the three modes;the three modes are shown below.The declaration of the function is given below.

int setvbuf(FILE * restrict stream,
char * restrict buf ,
int mode , size_t size);

Parameters:
stream -A FILE* variable.

buf -A pointer pointing to the buffer.

mode -The mode of the stream.It determines the type of buffering the stream should prefer.It can be any of the three modes given below

 _IOFBF:The buffer is filled completely before the data is written from the source file to the destination file.

 _IOLBF:The characters are placed in the buffer until one of the characters is a newline character or until the buffer is full.

 _IONBF:Data are read from and written directly to the file,the buffer is ignored.

size -The size of the buffer.

Return type
int-Returns zero on success,or nonzero if an invalid value is given for mode or if the request cannot be honored.

***Note you can only call setvbuf() if the file is opened successfully and before any input and output operation is performed.

Link :C fopen stdio.h

Code example

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

const siz=1024 ;

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

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

fputs( “Using setvbuf() function ” , 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,

Using setvbuf() function

Note in the above program the fourth argument value should be same as the size of the memory pointed by the ‘buf’ pointer.

Link :C fclose stdio.h





Some points to note

If the second argument is a null pointer

If the second argument passed to the setvbuf() function is a null pointer then the setvbuf() function will use the buffer allocated by the setvbuf() itself.

Code example

/*Checking the size of BUFSIZ */

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

char *buf=NULL ;

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

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

fclose( fp );

Here setvbuf() allocate a memory of size BUFSIZ and use that as a buffer.


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 setbuf stdio.h

->C malloc stdlib.h