Skip to study material
← Question index

QUESTION 08

Explain fread and fwrite with a binary-file example.

5 marks

Answer in brief

fread and fwrite transfer fixed-size elements between a stream and suitable memory objects.

Syntax

fwrite(array, sizeof array[0], count, fp);
fread(array, sizeof array[0], count, fp);

Algorithm

  1. Open the sample file with wb and check success.
  2. Write all requested elements and check the count.
  3. Close successfully, reopen with rb and check success.
  4. Read into storage large enough for the requested count.
  5. Use only valid completely read elements, then close.

Example

The program writes three ints, 10, 20 and 30. It reopens the file and reads exactly three ints into another array, then prints them. The native representation is used within one execution on the same implementation.

Short operations

A read requesting ten records may obtain fewer because the file ends. Never loop over all ten as though the missing records had been read. A partial final record is not a complete valid record merely because some bytes were obtained. Inspect stream errors and validate file structure for a real application.

Memory and complexity

The destination must have enough actual space and a suitable type. Transferring n fixed-size elements involves O(n) element work in the ordinary analysis, plus stream costs. The fixed buffer in this example has three elements. Native binary data is implementation-dependent and should not be described as a portable database format.

Complete C example

This demonstration creates or replaces its codebhavya_* sample file in the working directory. Run it in a separate test directory. Native binary examples use one compatible implementation.

main.c

Download main.c
/* CodeBhavya | Data Structures AR25 | Learning example */
#include <stdio.h>

int main(void)
{
    int input[3] = {10, 20, 30}, output[3];
    FILE *fp = fopen("codebhavya_binary_demo.bin", "wb");
    if (fp == NULL) { puts("Open failed"); return 1; }
    if (fwrite(input, sizeof input[0], 3, fp) != 3) { fclose(fp); puts("Write failed"); return 1; }
    if (fclose(fp) != 0) { puts("Close failed"); return 1; }
    fp = fopen("codebhavya_binary_demo.bin", "rb");
    if (fp == NULL) { puts("Open failed"); return 1; }
    if (fread(output, sizeof output[0], 3, fp) != 3) { fclose(fp); puts("Read failed"); return 1; }
    if (fclose(fp) != 0) { puts("Close failed"); return 1; }
    for (int i = 0; i < 3; ++i) { printf("%d\n", output[i]); }
    return 0;
}

Sample input and output

The example uses values in the code.

Output

10
20
30