ada Create And Write To A Stream


Example

The subtypes' stream-oriented attributes are called to write objects to a file, bare and using binary default representations.

with Ada.Streams.Stream_IO;

procedure Main is
   type Fruit is (Banana, Orange, Pear);
   type Color_Value is range 0 .. 255;
   type Color is record
      R, G, B : Color_Value;
   end record;

   Fruit_Colors : constant array (Fruit) of Color :=
     (Banana => Color'(R => 243, G => 227, B => 18),
      Orange => Color'(R => 251, G => 130, B => 51),
      Pear   => Color'(R => 158, G => 181, B => 94));

   use Ada.Streams.Stream_IO;

   F : File_Type;

begin
   Create (F, Name => "file.bin");
   for C in Fruit_Colors'Range loop
      Fruit'Write (Stream (F), C);
      Color'Write (Stream (F), Fruit_Colors (C));
   end loop;
   Close (F);
end Main;

Resulting File

00000000  00 2e f3 00 e3 00 12 00  01 2e fb 00 82 00 33 00
00000010  02 2e 9e 00 b5 00 5e 00