đŸ–Ĩ OS.IO.Arg Command Line Arguments - JulTob/Ada GitHub Wiki

Command-Line Arguments

There will be times when you will want to start up your application and put in certain variables at startup. Basically, these are settings that you set once when the program starts and continue (unless changed internally) to be set. We call these variables command-line arguments. You would set them when you first start up the program at the command line. Here is an example that illustrates this:

-- command_line_arguments.adb:
with Ada.Command_Line;
with Ada.Text_IO;
procedure Command_Line_Arguments is
begin
  -- this will print out the name of the application.
  Ada.Text_IO.Put_Line("Application name and path: " &
    Ada.Command_Line.Command_Name);
  for Arg in 1 .. Ada.Command_Line.Argument_Count loop
    Ada.Text_IO.Put_Line(Ada.Command_Line.Argument(Arg) & " ");
  end loop;
end Command_Line_Arguments;


ere is what is going on in the preceding snippet:

  1. with Ada.Command_Line; – This is the package that is necessary in order to work with command-line arguments.
  2. On line 9, this is what will show the name of the application as well as the directory of the application: Ada.Command_Line.Command_Name This is useful for debug purposes also. The preceding function will print out the name of your application and its location in the file system; the author will confess that he has wasted many hours trying to figure out why his application does not have the latest feature only to find out that he was running the wrong binary.
  3. for Arg in 1 .. Ada.Command_Line.Argument_Count loop – In this loop an artificial range is created from the value of 1 to Argument_Count. When your application starts, the Argument_ Count includes the total number of passed in arguments that were passed into it. This is useful for when you want to put things into a for loop and iterate over the arguments one by one.
  4. Ada.Text_IO.Put_Line(Ada.Command_Line.Argument(Arg) & " "); – Building on top of the preceding example, you make use of a generated array that gives you the passed in command-line arguments, which is what happens when the Arg variable goes into it (from the previous line in the for loop).