Exercises in this lecture   Go to the notes, in which this exercise belongs -- Keyboard shortcut: 'u'   Alphabetic index   Course home   

Exercise solution:
Die tossing - writing to a binary file


There are only a few differences between this solution and the corresponding text file solution.

The output part of the program is here:

using System;
using System.IO;

class C{

  public static void Main(){

    Die d = new Die();
    using(BinaryWriter tw = new BinaryWriter(new FileStream("die.bin", FileMode.Create))){
      for(int i = 1; i <= 1000; i++){
        d.Toss();
        tw.Write(d.NumberOfEyes());
      }
   }

  }

}

The size of the binary file is 4000 bytes, namely four bytes per integer. (This is actually waste of space. Can you do it better?) The size of the text file generated by the program from the previous exercise is 3000 bytes, namely one byte representing either '1', '2', '3', '4', '5', or '6' and two bytes for newline and carriage return (Windows end-of-line convention). Notice that we - in general - expect smaller binary files than the similar text files!

The reading part of the program is here:

using System;
using System.IO;

class C{

  public static void Main(){

    int[] count = new int[7];  // use 1..6.
    int numberOfEyes;

    for(int i = 1; i <= 6; i++) count[i] = 0;

    using(BinaryReader tr = new BinaryReader(new FileStream("die.bin", FileMode.Open))){
      for(int i = 1; i <= 1000; i++){
        numberOfEyes = tr.ReadInt32();
        count[numberOfEyes]++;
      }
   }

   for(int i = 1; i <= 6; i++)
     Console.WriteLine("Number of {0}: {1}", i, count[i]);

  }

}