This is a follow-up of this question: Ada: reading from a file .
I would like to add an exception
that checks if the file that I'm opening actually exists or not. I have made a separate
procedure to avoid code clutter.
Here is the main code test_read.adb
:
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Long_Float_Text_IO;
with Ada.Float_Text_IO;
procedure Test_Read is
Input_File : File_Type;
Value : Long_Float;
procedure Open_Data (File : in Ada.Text_IO.File_Type; Name : in String) is separate;
begin
Ada.Text_IO.Open (File => Input_File, Mode => Ada.Text_IO.In_File, Name => "fx.txt");
while not End_Of_File (Input_File) loop
Ada.Long_Float_Text_IO.Get (File => Input_File, Item => Value);
Ada.Long_Float_Text_IO.Put (Item => value, Fore => 3, Aft => 5, Exp => 0);
Ada.Text_IO.New_Line;
end loop;
Ada.Text_IO.Close (File => Input_File);
end Test_Read;
And here is the separate
body test_read-open_data.adb
of the procedure Open_Data
:
separate(test_read)
procedure Open_Data (File : in out Ada.Text_IO.File_Type;
Name : in String) is
--this procedure prepares a file for reading
begin
begin
Ada.Text_IO.Open
(File => File,
Mode => Ada.Text_IO.In_File,
Name => Name);
exception
when Ada.Text_IO.Name_Error =>
Ada.Text_IO.Put(File => Standard_Error, Item => "File not found.");
end;
end Open_Data;
On compilation I get an error message in the separate
body test_read-open_data.adb
:
actual for "File" must be a variable
How to fix this?
Thanks a lot...
Update:
I have now made the following corrections.
In
test_read.adb
, I now haveprocedure Open_Data (File : in out Ada.Text_IO.File_Type; Name : in String) is separate;
Updated the definition of the same
Open_Data
procedure intest_read-open_data.adb
.
The program compiles well though I do not see it catch the exception say if I renamed the file fx.txt
to fy.txt
. The error message I get is just
raised ADA.IO_EXCEPTIONS.NAME_ERROR : fx.txt: No such file or directory
So I do not get my own error message :File not found.
What is still wrong?
if your goal is to simply check if the file exists, consider using Ada.Directories.Exists
IIRC: Standard_Error is not a file, but a Stream.
The
File
parameter of Open_Data needs to be anin out
parameter (as in, for example,Ada.Text_IO.Create
), because you want the opened file to be accessible withinTest_Read
.You are getting
actual for "File" must be a variable
because anin
parameter is read-only.(Personally I rarely type the
in
mode, because it’s the default).But in any case, it looks as though the reason for the observed behaviour is that
Test_Read
doesn’t actually callOpen_Data
!(edited to make the recommended mode
in out
& to suggest callingOpen_Data
)I suspect that the reason you are not seeing your error message is that you are using Put rather than Put_Line. Different implementations/platforms treat output to the user's display differently. To be extra sure you will see the message, follow the Put_Line with a Get_Line. The Get_Line generally forces the output of the Put_Line.