gtpc2m6aC/C++ Language Support User's Guide

setbuf-Control Buffering

This function controls buffering.

Format

#include <stdio.h>
void setbuf(FILE *stream, char *buffer);

stream
The newly opened file.

buffer
The user-supplied buffer.

This function controls the way data is buffered for the specified stream. The stream pointer must refer to an open file and the setbuf function must be the first operation on the stream.

If the buffer argument is NULL, the stream is unbuffered. If not, the stream will be full buffered and the buffer must point to an array length of at least BUFSIZ characters defined in the stdio.h header file. Input/Output (I/O) functions may use the buffer, which you specify here, for input/output buffering instead of the default system-allocated buffer for the given stream.

Note:
If you use the setbuf or setvbuf function to define your own buffer for a stream, you must ensure that the buffer is available the whole 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 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, make the buffer a variable allocated at file scope. This can be done 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.

Normal Return

There is no returned value.

Error Return

Not applicable.

Programming Considerations

Your buffer will only be as large as BUFSIZ. If you define the buffer to be larger than BUFSIZ, your buffer will be limited to BUFSIZ.

Examples

The following example opens the myfile.dat file for writing. It then calls the setbuf function to establish a buffer of length bufsiz.

#include <stdio.h>
 
int main(void)
{
   char buf[BUFSIZ];
   char string[] = "hello world";
   FILE *stream;
 
   stream = fopen("myfile.dat", "wb");
   setbuf(stream,buf);       /* set up buffer */
 
   fwrite(string, sizeof(string), 1, stream);
 
   fclose(stream);
}
   /* Note that the stream is closed before the buffer goes out */
   /* of scope at the end of this block.                        */

Related Information

See Appendix E, Programming Support for the TPF File System for more information about TPF File System C Functions.