fwrite() function in C

Binary Input and Output

Up to this point, we have been using text mode to read and write data to and from the file. In this chapter, we will learn how we can read and write data to and from the file using the binary mode. Recall that in binary mode data is stored in the file in the same way as in the memory, so no transformation of data takes place in binary mode. As no transformation takes place binary mode is significantly faster than text mode.

[img]

fread() and fwrite() functions are commonly used to read and write binary data to and from the file respectively. Although we can also use them with text mode too.

Let's start with fwrite() function.

fwrite() function

Syntax: size_t fwrite(const void *ptr, size_t size, size_t n, FILE *fp);

fwrite() function writes the data specified by the void pointer ptr to the file.

ptr: it points to the block of memory which contains the data items to be written.

size: It specifies the number of bytes of each item to be written.

n:  It is the number of items to be written.

fp: It is a pointer to the file where data items will be written.

On success, it returns the count of the number of items successfully written to the file. On error, it returns a number less than n. Notice that two arguments (size and n) and return value of fwrite() are of type size_t which on the most system is unsigned int.

To better understand fwrite() function consider the following examples :

Example 1: Writing a variable

float *f = 100.13;

fwrite(&p, sizeof(f), 1, fp);

This writes the value of variable f to the file.

Example 2: Writing an array

int arr[3] = {101, 203, 303};

fwrite(arr, sizeof(arr), 1, fp);

This writes the entire array into the file.

Example 3: Writing some elements of array

int arr[3] = {101, 203, 303};

fwrite(arr, sizeof(int), 2, fp);

This writes only the first two elements of the array into the file.

Example 4: Writing structure

struct student
{
    char name[10];
    int roll;
    float marks;
};

struct student student_1 = {"Tina", 12, 88.123};

fwrite(&student_1, sizeof(student_1), 1, fp);

This writes contents of variable student_1 into the file.

Example 5: Writing array of structure

struct student
{
    char name[10];
    int roll;
    float marks;
};

struct student students[3] = {
                                 {"Tina", 12, 88.123},
                                 {"Jack", 34, 71.182},
                                 {"May", 12, 93.713}
                             };

fwrite(students, sizeof(students), 1, fp);

This writes the whole array students into the file.

Let's say we don't' want to write all elements of the array into the file, instead, we want is to write only 0th and 1st element of the array into the file.

fwrite(students, sizeof(struct student), 2, fp);

Now you have understood how fwrite() function works. Let's create a program using fwrite() function.

The following program demonstrates how to use fwrite() function.

#include<stdio.h>
#include<stdlib.h>

struct employee
{
    char name[50];
    char designation[50];
    int age;
    float salary
} employee;

int main()
{
    int n, i, chars;
    FILE *fp;

    fp = fopen("employee.txt", "wb");

    if(fp == NULL)
    {
        printf("Error opening file\n");
        exit(1);
    }

    printf("Testing fwrite() function: \n\n");

    printf("Enter the number of records you want to enter: ");
    scanf("%d", &n);

    for(i = 0; i < n; i++)
    {
        printf("\nEnter details of employee %d \n", i + 1);

        fflush(stdin);

        printf("Name: ");
        gets(employee.name);
        
        printf("Designation: ");
        gets(employee.designation);
        
        printf("Age: ");
        scanf("%d", &employee.age);
        
        printf("Salary: ");
        scanf("%f", &employee.salary);
        
        chars = fwrite(&employee, sizeof(employee), 1, fp);
        printf("Number of items written to the file: %d\n", chars);
    }

    fclose(fp);
    return 0;
}

Expected Output:

Testing fwrite() function:

Enter the number of records you want to enter: 2

Enter details of employee 1
Name: Bob
Designation: Manager
Age: 29
Salary: 34000
Number of items written to the file: 1

Enter details of employee 2
Name: Jake
Designation: Developer
Age: 34
Salary: 56000
Number of items written to the file: 1

How it works

In lines 4-10, a structure employee is declared which has four members namely name is an array of characters, designation is also an array of characters, age is of type int and salary is of type float. Along with the structure definition, a variable emp of type struct employee is also declared.

In line 14, three variables n, i and chars are declared of type int.

In line 15, a structure pointer fp of type struct FILE is declared.

In line 17, fopen() function is called with two arguments namely "employee.txt" and "wb". On success, it returns a pointer to file employee.txt and opens the file employee.txt in write-only mode. On failure, it returns NULL.

In lines 19-23, if statement is used to test the value of fp. If it is NULL, printf() statement prints the error message and program terminates. Otherwise, the program continues with the statement following the if statement.

In lines 27-28, the program asks the user how many records he/she wants to enter and stores the number in the variable n.

In lines 30-50, the statements in the for loop asks the user to enter four pieces of information namely name, designation, age and salary. Notice that in line 34 fflush() function is called to flush(remove) the newline character from the standard input which was entered while entering the number of records in line 28. If there had been no call to fflush(stdin) then gets() function in line 37 would have read the newline character from the standard input and doesn't wait for user input. In line 48, fwrite() function is called to write the structure variable emp into the file in binary mode. We already know that on success fwrite() returns the number of items written to the file. Here we are writing the data of a single structure variable so fwrite() will return 1. On error, it will return a number less than 1. The return value of fwrite() is then assigned to the chars variable. In line 49, the printf() statement prints the number of items successfully written to the file.

In line 52, fclose() function is used to close the file.