setbuf() function in C++

In this guide, you will learn what is setbuf() function is in C++ programming and how to use it with an example.

1. setbuf() Function Overview

The setbuf() function is part of the <cstdio> library in C++. It is used to control buffering for a specified stream. By default, streams like stdout are line-buffered when they refer to terminal devices and fully buffered otherwise. The setbuf() function allows us to set a buffer for a stream or disable buffering entirely.

Signature:

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

Parameters:

- stream: The stream for which the buffer is being set.

- buffer: A pointer to a buffer where stream data will be buffered. If this parameter is a NULL pointer, buffering will be disabled for the stream.

2. Source Code Example

#include <iostream>
#include <cstdio>

int main() {
    char buf[BUFSIZ];  // BUFSIZ is defined in <cstdio> and represents a system-determined buffer size

    FILE* pFile = fopen("example.txt", "w");

    if (pFile == nullptr) {
        std::cerr << "Error opening file." << std::endl;
        return 1;
    }

    // Set buffer for pFile
    setbuf(pFile, buf);

    fputs("This is an example.", pFile);

    // Close the file
    fclose(pFile);

    std::cout << "Data written to the file successfully." << std::endl;

    return 0;
}

Output:

Data written to the file successfully.

(Note: An "example.txt" file will be created with the content "This is an example.")

3. Explanation

1. We first open a file named "example.txt" in write mode.

2. A buffer of size BUFSIZ is defined. The BUFSIZ macro is provided by <cstdio> and is optimal for system I/O operations.

3. The setbuf() function is then used to set the buffer for the pFile stream.

4. Data is written to the file using the fputs() function.

5. Finally, the file is closed using fclose().


Comments