Section 9.1 - Simple Text File Input/Output

Throughout this tutorial we've been using selected input/output subprograms, mainly from the predefined package Text_IO. Now it's time to learn how to use more capabilities of Text_IO, especially how to read and write text files.

Operating system files are represented in Text_IO by a type called, reasonably enough, File_Type. All operations on files operate on objects of type File_Type. The default for inputting operations (such as Get) is Current_Input (Current_Input is of type File_Type), while the default for all outputting operations (such as Put and Put_Line) is Current_Output (which also has type File_Type).

Before a text file can be read or written it must be either opened or created. There are two basic procedures in Text_IO, called, naturally enough, Open and Create. Open opens an existing file, while Create creates a new file (eliminating the original file) and then opens it. Before you stop your program you should close all the files you've opened; the Close procedure is used to do that. Here are their definitions:

  procedure Create (File : in out File_Type;
                    Mode : in File_Mode := Out_File;
                    Name : in String    := "";
                    Form : in String    := "");

  procedure Open   (File : in out File_Type;
                    Mode : in File_Mode;
                    Name : in String;
                    Form : in String := "");

  procedure Close  (File : in out File_Type);

The ``Mode'' can be In_File (an input file), Out_File (an output file), or Append_File (an output file appending after existing text). The ``Form'' parameter is optional, and is used to provide operating-system-specific information if it's necessary.

All the Get and Put subprograms can take a parameter of type File_Type as their first parameter; if they're handed a File_Type, the subprogram will read or write to the given file. In general, if you don't want to use the default File_Type, add the File_Type as the first parameter of an input-output subprogram.

Here's a trivial example - a program that creates a new file called "hi" and writes text into it:

with Text_IO;
use  Text_IO;

procedure Make_Hi is
  New_File : File_Type;
  Create(New_File, Out_File, "hi");
  Put_Line(New_file, "Hi, this is a test!");
end Make_Hi;


If you ran program Make_Hi twice, how many text lines would the file "hi" contain when you were done?

  1. 1.
  2. 2.
  3. None.

You may also:

PREVIOUS Go back to the previous section

NEXT     Skip to the next section

OUTLINE  Go up to lesson 9 outline

David A. Wheeler (

The master copy of this file is at "".