Previous topic | Next topic | Ada Home Page | Index

Using Files in Ada Programs

Files need to be:

  1. declared
  2. created/opened/reset
  3. used for I/O
  4. closed

An example program shows how the contents of one file can be copied to another. The program includes all of the elements listed above and described below.


File operations

Declaring Text Files

        with TEXT_IO;

        ...

        filevar : TEXT_IO.FILE_TYPE;

Commonly two file variables

Data type for file variable:


Preparing Files

Open an existing file for input:

        OPEN   (FILE => filein,
                MODE => IN_FILE,
                NAME => "oldstu.dat");

        OPEN   (filein,  IN_FILE, "oldstu.dat");

Create a new file for output:

        CREATE (FILE => fileout,
                MODE => OUT_FILE,
                NAME => "newstu.dat");

        CREATE (fileout, "newstu.dat");

Open an existing file for output (over-write its contents):

        OPEN   (FILE => fileout,
                MODE => OUT_FILE,
                NAME => "newstu.dat");

        OPEN   (fileout, OUT_FILE, "newstu.dat");

RESET

Sometimes a program needs to process a file twice

You could always close the file, and then reopen it, but Ada provides a shortcut for this situation.

RESET procedure:

Example: read file twice

        OPEN (filevar, IN_FILE, filename);
        ... code to read from the file ...
        RESET (filevar);
        ... code to read the file all over again ...
        CLOSE (filevar);

Example: write, then read

        CREATE (filevar, OUT_FILE, filename);
        ... code to write to the file ...
        RESET (filevar, IN_FILE);
        ... read the information just written ...
        CLOSE (filevar);


Using files for I/O

PUT, GET etc may have a file variable as first argument

        PUT ("message");                 -- to screen

        PUT (fileout, "message");        -- to file

        SET_COL (fileout, 5);
        PUT     (fileout, "message");


Closing Files

Always close files when finished with them
        CLOSE (filevar);


Treating the terminal as a text file

Ada lets you treat the terminal as a text file (or files).

Input from keyboard:

	GET (num);
	GET (STANDARD_INPUT, num);

Output to screen:

	PUT ("message");
	PUT (STANDARD_OUTPUT, "message");


Previous topic | Next topic | Ada Home Page | Index
c-lokan@adfa.oz.au / 23 Feb 96