サーチ…


備考

Ada標準ライブラリは、テキストファイルやバイナリデータの従来のファイルのI / O、ストリームファイルのI / Oを提供します。バイナリデータのファイルはあるタイプの値のシーケンスであり、ストリームファイルはおそらく異なるタイプの値のシーケンスである。

さまざまなタイプの要素をストリームファイルとの間で読み書きするために、Adaは型の属性、つまり'Read 'Write'Write 'Input'Input 」、 'Output 」で示されるサブプログラムを使用します。後者の2つは、 Read'Writeが実行する裸の入出力に加えて、配列境界、レコード判別式、およびタイプタグ'Writeます。

ファイルの作成と書き込み

パッケージAda.Text_IOからのCreatePut_LineCloseプロシージャは、 file.txtファイルの作成と書き込みに使用されます。

with Ada.Text_IO;

procedure Main is
   use Ada.Text_IO;
   F : File_Type;
begin
   Create (F, Out_File, "file.txt");
   Put_Line (F, "This string will be written to the file file.txt");
   Close (F);
end;

結果ファイルfile.txt

This string will be written to the file.txt

作成してストリームに書き込む

サブタイプのストリーム指向の属性は、オブジェクトをファイルに書き込むために呼び出され、裸で、バイナリのデフォルト表現を使用します。

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;

結果ファイル

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                         

ストリームファイルを開いて読み込む

ストリームの作成と書き込みのデータをプログラムに読み戻します。

with Ada.Streams.Stream_IO;

procedure Main is
   --
   --  ... same type definitions as in referenced example
   --
   Fruit_Colors : array (Fruit) of Color;

   use Ada.Streams.Stream_IO;

   F : File_Type;
   X : Fruit;
begin
   Open (F, Mode => In_File, Name => "file.bin");
   loop
      Fruit'Read (Stream (F), X);
      Color'Read (Stream (F), Fruit_Colors (X));
   end loop;
exception
   when End_Error =>
      Close (F);
   pragma Assert  -- check data are the same
     (Fruit_Colors (Banana) = Color'(R => 243, G => 227, B => 18) and
      Fruit_Colors (Orange) = Color'(R => 251, G => 130, B => 51) and
      Fruit_Colors (Pear)   = Color'(R => 158, G => 181, B => 94));
end Main;


Modified text is an extract of the original Stack Overflow Documentation
ライセンスを受けた CC BY-SA 3.0
所属していない Stack Overflow