2

I have the following fragment of code

 with GNAT.Command_Line; use GNAT.Command_Line;
 with GNAT.Strings;      use GNAT.Strings;

 ....

 Define_Switch
           (Config      => Config, Output => File_Name'Access,
            Long_Switch => "--file=", Switch => "-f=",
            Help        => "File with Composition");

 ....
  Getopt

After parsing command line via Getopt I have access object that points to actual file name I would like to copy this name to Ada.String.Fixed string that definded as

 File_Name : String(1 .. 256);

I can print to console data from File_Name'Access as

Put_Line(File_Name.all);

I think I should provide something like copy operation then free access object. How can I do it?

Thanks. Alex

Chris
  • 26,361
  • 5
  • 21
  • 42
Alexander
  • 342
  • 4
  • 14

1 Answers1

5

I guess File_Name in the code snippet defined as 'aliased GNAT.Strings.String_Access'. This is a "fat pointer" to the string object. "Fat" means it is not an address only, it is range of indices of the string. C-style Nil terminator is not used in Ada, and Nil is valid character.

You can copy data inside this string object into the another standard String object playing with indexes computations, but usually you must not do this: there is no Nil terminator, you will need to pass length of the actual data; destination string object may be smaller than necessary, and data will be truncated or exception raised; etc.

There are two right ways to do this. First one is to declare unconstrained string object and assign value to it.

declare
   Fixed_File_Name : String := File_Name.all;

begin
   Free (File_Name);

or use variable length string (bounded or unbounded):

declare
   Unbounded_File_Name : Ada.Strings.Unbounded.Unbounded_String;

begin
   Unbounded_File_Name :=
     Ada.Strings.Unbounded.To_Unbounded_String (File_Name.all);
   Free (File_Name.all);

Use of fixed string has important restriction: string object must be initialized exactly at the point of declaration of the object, and available only inside corresponding block/subprogram. Use of variable length string allows to declare string object outside of the scope of particular block/subprogram.