In: Computer Science
I try to invent the examples, but I can't still.
I do not understand how setvbuf can be useful, and also I don't
understand with setbuf. please explain setvbuf vs setoff
setbuf( ): This function associates with the buffer with the
specified stream. setbuf() will let us change the way,how a stream
will buffered , & to control the size and location of the
buffer.
void setbuf( FILE *fp, char *buffer );
Here,
Fp:
The stream that we want to associate with a buffer.
Buffer:
NULL, or a pointer to the buffer.
Here, the parameter stream is the pointer of stream file, and the
BUF is the initial address of the buffer.
When, buffer argument is NULL, the stream is unbuffered. When
,Buffer parameter is not null character pointer, then the array it
points to is used for the buffering.
setbuf() is also implement the ability to manipulate the flow of
file directly when manipulating the buffer.
setbuf() function only works with ILE C when we using the
integrated file system. Stream pointer must
refer to the open file before any I/O has been done.
Example : set the buffer that will stream use.
int main ()
{
char buffer[BUFSIZ];
FILE *fp1, *fp2;
fp1=fopen ("check.txt","A"); //open file
fp2=fopen ("find.txt","B");
setbuf ( fp1 , buffer ); // controlling buffering
fputs ("File will sent to buffered stream",fp1);
fflush (fp1); // write buffer to file
setbuf ( fp2 , NULL ); // controlling buffering
fputs ("File will sent to unbuffered stream",fp2);
//Set buf to null to turning off the buffering.
//BUFSIZ is defined in the <stdio.h>.
fclose (fp1); //close stream
fclose (fp2);
return 0;
}
The setvbuf() is more capable than setbuf().
Setvbuf() will assign the buffering to a stream.
setvbuf () is used to set the buffer for a file stream, and it’s
prototype :
int setvbuf ( FILE * stream, char * buf, int type/ mode, size_t
size );
Here, the parameter “stream” is a pointer to file stream, &
“buf” is the buffer's first address, “type” is the type of buffer,
& the “size” is the number of bytes in the buffer.
setvbuf() function can be used on any open stream to change its
buffer.
#include <stdio.h>
int main ()
{
FILE *pFile;
pFile=fopen ("search.txt","s"); // open file
setvbuf ( pFile , NULL , _IOFBF , 1024 ); // buffer of 1024
bytes is requested for the stream
// Specifies a buffer for the stream
// File operations
fclose (pFile); // close the file
return 0;
}
_IOFBF Full buffering: On output, data written once the
buffer is full.
_IOLBF Line buffering: On output, data is written when
a newline character is inserted into the stream _IONBF
No buffering: No buffer will used. I/O operation written as soon as
possible.