Redirecting Text_IO output to a file

One, probably not so often used, feature of Ada.Text_IO is an ability to redirect output (Put, Put_Line, Newline) to a file. It happens simply by opening a file where you want to redirect the output and then calling Set_Output procedure.

Example below shows how it is done:

with Ada.Text_IO;

procedure Redir is
   Handle : Ada.Text_IO.File_Type;
   Ada.Text_IO.Create (Handle, Ada.Text_IO.Out_File, "out.txt");

   Ada.Text_IO.Put_Line ("Starting redirection to out.txt");

   -- Tell Text_IO to redirect all output to Handle
   Ada.Text_IO.Set_Output (Handle);

   -- Print some text
   Ada.Text_IO.Put_Line ("Hello, this will go to out.txt");

   Ada.Text_IO.Close (Handle);

   -- Restoring output back to standard output
   Ada.Text_IO.Set_Output (Ada.Text_IO.Standard_Output);
   Ada.Text_IO.Put_Line ("Redirection restored to standard output");
end Redir;

This technique is used for example in Ahven framework, see ahven-temporary_output.adb for details.

EDIT 2014-03-20: Removed all Flush calls, they were useless.