OverIQ.com

fwrite() Function in C

Last updated on July 27, 2020


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);

The 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

1
2
3
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

1
2
3
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

1
2
3
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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
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.