fwrite() function in C++

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

1. fwrite() Function Overview

The fwrite() function is used to write data from an array to a file. It writes a specified number of elements of a given size to the file stream from the specified memory location.

Signature:

size_t fwrite(const void* ptr, size_t size, size_t count, FILE* stream);

Parameters:

- ptr: A pointer to the array of elements to be written.

- size: The size in bytes of each element to be written.

- count: The total number of elements to be written.

- stream: Pointer to a FILE object that specifies an output stream.

2. Source Code Example

#include <iostream>
#include <cstdio>

int main() {
    FILE* fp;
    const char* data = "Hello, World!";

    // Open file in write mode
    fp = fopen("output.txt", "w");
    if(fp == NULL) {
        std::cerr << "Error opening file.";
        return 1;
    }

    // Using fwrite to write data to the file
    size_t result = fwrite(data, sizeof(char), strlen(data), fp);
    if(result == strlen(data)) {
        std::cout << "Data successfully written to the file." << "\n";
    } else {
        std::cerr << "Error writing to file.";
    }

    // Close the file
    fclose(fp);

    return 0;
}

Output:

Data successfully written to the file.

3. Explanation

1. We declare a FILE pointer named fp and a constant character pointer data containing a message.

2. We open a file named "output.txt" in write mode.

3. If the file opens successfully, we use fwrite() to write data from the data variable to the file.

4. We then check if the number of written characters matches the length of our message to ensure successful writing.

5. After writing to the file, we close it using fclose().


Comments