Reading Files in Ada

Our first example demonstrates reading files in Ada. Reading files is a basic task needed for many Ada programs. Let’s look at some examples of reading files.

with Ada.Text_IO;
with Ada.Streams.Stream_IO;
with Ada.Exceptions;

procedure Read_Files is
   use Ada.Text_IO;
   use Ada.Streams.Stream_IO;
   use Ada.Exceptions;

   procedure Check(E : Exception_Occurrence) is
   begin
      if E /= Null_Occurrence then
         Raise_Exception(Exception_Identity(E), Exception_Message(E));
      end if;
   end Check;

   File : File_Type;
   S : Stream_Access;
   Bytes_Read : Natural;
begin
   -- Reading entire file contents into memory
   declare
      Content : String := Get_Line(Open(Name => "/tmp/dat", Mode => In_File));
   begin
      Put_Line(Content);
   end;

   -- Opening a file to obtain more control
   Open(File, In_File, "/tmp/dat");
   S := Stream(File);

   -- Read some bytes from the beginning of the file
   declare
      B1 : String(1..5);
   begin
      String'Read(S, B1);
      Put_Line(Natural'Image(B1'Length) & " bytes: " & B1);
   end;

   -- Seek to a known location and read from there
   Set_Index(File, 7);
   declare
      B2 : String(1..2);
   begin
      String'Read(S, B2);
      Put_Line("2 bytes @ 6: " & B2);
   end;

   -- Seek relative to current position
   Set_Index(File, Index(File) + 4);

   -- Seek relative to end of file
   Set_Index(File, Size(File) - 9);

   -- Read at least a certain number of bytes
   Set_Index(File, 7);
   declare
      B3 : String(1..2);
   begin
      String'Read(S, B3);
      Put_Line("2 bytes @ 6: " & B3);
   end;

   -- Rewind to the beginning of the file
   Reset(File);

   -- Using a buffered reader
   declare
      Line : String := Get_Line(File);
   begin
      Put_Line("5 bytes: " & Line(1..5));
   end;

   -- Close the file when done
   Close(File);
exception
   when E : others =>
      Check(E);
end Read_Files;

To run the program, first create a file with some content:

$ echo "hello" > /tmp/dat
$ echo "ada" >> /tmp/dat

Then compile and run the Ada program:

$ gnatmake read_files.adb
$ ./read_files
hello
ada
5 bytes: hello
2 bytes @ 6: ad
2 bytes @ 6: ad
5 bytes: hello

This example demonstrates various file reading operations in Ada, including reading entire file contents, reading specific bytes, seeking to different positions in the file, and using buffered reading. The Ada.Streams.Stream_IO package provides similar functionality to Go’s io package, allowing for low-level file operations.

Next, we’ll look at writing files in Ada.