fprintf() function in C++

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

1. fprintf() Function Overview

The fprintf() function is part of the <cstdio> library in C++. It allows for formatted output to a specified stream, most commonly used for writing formatted strings to files. It is analogous to the printf() function, but instead of writing to the standard output, it writes to a given file stream.

Signature:

int fprintf(FILE* stream, const char* format, ...);

Parameters:

- stream: Pointer to the file stream where the formatted output should be written.

- format: A string that specifies how the subsequent arguments are converted for output.

- ...: Variable number of arguments that will be formatted and printed according to the format string.

2. Source Code Example

#include <iostream>
#include <cstdio>

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

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

    // Write formatted data to the file
    int age = 25;
    const char* name = "John Doe";
    fprintf(pFile, "Name: %s\nAge: %d", name, age);

    // 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:
Name: John Doe
Age: 25
)

3. Explanation

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

2. The fprintf() function is then used to write a formatted string to the pFile stream. The %s format specifier is replaced by the string name, and the %d format specifier is replaced by the integer age.

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


Comments