setbuf() — Control Buffering

Standards / Extensions C or C++ Dependencies
ISO C
POSIX.1
XPG4
XPG4.2
both  

Format

#include <stdio.h>

void setbuf(FILE *stream, char *buffer);

General Description

Controls buffering for the specified stream. The stream pointer must refer to an open file, and setbuf() must be the first operation on the stream.

If buffer is NULL, the stream is unbuffered. If not, the buffering mode will be full buffer and the buffer must point to a character array of length at least BUFSIZ, which is the buffer size defined in the stdio.h header file. I/O functions use the buffer, which you specify here, for input/output buffering instead of the default system-allocated buffer for the given stream. If the buffer does not meet the requirements of IBM® XL C/C++ for z/VM®, the buffer is not used.

The setvbuf() function is more flexible than setbuf(), because you can specify the type of buffering and size of the buffer.

Attention: If you use setvbuf() or setbuf() to define your own buffer for a stream, you must ensure that the buffer is available the entire time that the stream associated with the buffer is in use.

For example, if the buffer is an automatic array (block scope) and is associated with the stream s, leaving the block causes the storage to be deallocated. I/O operations of stream s are prevented from using deallocated storage. Any operation on s would fail because the operation would attempt to access the nonexistent storage.

To ensure that the buffer is available throughout the life of a program, you should make the buffer a variable allocated at file scope, by using an identifier of type array declared at file scope, or by allocating storage (with malloc() or calloc()) and assigning the storage address to a pointer declared at file scope.

CMS and VSAM file types do not support unbuffered I/O, causing requests for unbuffered I/O to fail.

Returned Value

The setbuf() function has no returned value. For details about errno values and buffers you may have set, see discussions about buffering in z/OS: XL C/C++ Programming Guide.

Example

CBC3BS01

/* CBC3BS01
   This example opens the file myfile.dat for writing.  It then calls
   the setbuf() function to establish a buffer of length BUFSIZ.
   When string is written to the stream, the buffer buf is used and
   contains the string before it is flushed to the file.
 */
#include <stdio.h>

int main(void)
{
   char buf[BUFSIZ];
   char string[] = "hello world";
   FILE *stream;

   stream = fopen("myfile.dat", "wb,recfm=f");

   setbuf(stream,buf);       /* set up buffer */

   fwrite(string, sizeof(string), 1, stream);

   printf("%s\n",buf);       /* string is found in buf now */

   fclose(stream);           /* buffer is flushed out to myfile.dat */
}