C fwrite() Function | Write Data to Files in C

Introduction

The fwrite() function in C is a standard library function that writes data from an array to a given stream. It is part of the C standard library (stdio.h) and is commonly used for binary file output operations.

fwrite() Function Syntax

The syntax for the fwrite() function is as follows:

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

Parameters:

  • ptr: A pointer to the block of memory containing the data to be written.
  • size: The size in bytes of each element to be written.
  • nmemb: The number of elements, each one with a size of size bytes.
  • stream: A pointer to a FILE object that specifies an output stream.

Returns:

  • The function returns the total number of elements successfully written. This number will be less than nmemb only if an error occurs.

Examples

Writing an Array of Integers

To demonstrate how to use fwrite() to write an array of integers to a binary file, we will write a simple program.

Example

#include <stdio.h>

int main() {
    FILE *file;
    int numbers[5] = {10, 20, 30, 40, 50};

    // Open the file for writing
    file = fopen("numbers.bin", "wb");
    if (file == NULL) {
        printf("Error: Could not open file for writing.\n");
        return 1;
    }

    // Write the array of integers to the file
    size_t elementsWritten = fwrite(numbers, sizeof(int), 5, file);
    if (elementsWritten != 5) {
        printf("Error: Could not write the correct number of elements.\n");
        fclose(file);
        return 1;
    }

    // Close the file
    fclose(file);

    return 0;
}

Output (content of numbers.bin):

(Binary representation of the integers 10, 20, 30, 40, 50)

Writing a Structure to a Binary File

This example demonstrates how to use fwrite() to write a structure to a binary file.

Example

#include <stdio.h>

typedef struct {
    char name[50];
    int age;
    float salary;
} Employee;

int main() {
    FILE *file;
    Employee emp = {"Ramesh Fadatare", 30, 60000.00};

    // Open the file for writing
    file = fopen("employee.bin", "wb");
    if (file == NULL) {
        printf("Error: Could not open file for writing.\n");
        return 1;
    }

    // Write the structure to the file
    size_t elementsWritten = fwrite(&emp, sizeof(Employee), 1, file);
    if (elementsWritten != 1) {
        printf("Error: Could not write the correct number of elements.\n");
        fclose(file);
        return 1;
    }

    // Close the file
    fclose(file);

    return 0;
}

Output (content of employee.bin):

(Binary representation of the Employee structure)

Real-World Use Case

Saving Configuration Data

In real-world applications, the fwrite() function can be used to save configuration data to a binary file for later retrieval.

Example

#include <stdio.h>

typedef struct {
    char url[100];
    int timeout;
    int maxConnections;
} Config;

int main() {
    FILE *file;
    Config config = {"http://example.com", 5000, 100};

    // Open the file for writing
    file = fopen("config.bin", "wb");
    if (file == NULL) {
        printf("Error: Could not open file for writing.\n");
        return 1;
    }

    // Write the configuration data to the file
    size_t elementsWritten = fwrite(&config, sizeof(Config), 1, file);
    if (elementsWritten != 1) {
        printf("Error: Could not write the correct number of elements.\n");
        fclose(file);
        return 1;
    }

    // Close the file
    fclose(file);

    return 0;
}

Output (content of config.bin):

(Binary representation of the Config structure)

Conclusion

The fwrite() function is used for writing binary data to files. It writes a specified number of elements of a specified size from a given block of memory to the specified stream.

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare