Previous topic | Next topic | Ada Home Page | Index

Reading a file of lines

Example

We have seen an example program that copies one file to another. It does so in complete lines, a line at a time.

Its heart is the following code:

        with TEXT_IO; use TEXT_IO;

        procedure copy_file is

            inf         : TEXT_IO.FILE_TYPE;   -- input file
            outf        : TEXT_IO.FILE_TYPE;   -- output file
            line        : string (1..200);     -- one line of a file
            line_length : NATURAL;             -- line length

	        ... 

        begin

            ...

            while not END_OF_FILE (inf) loop
                GET_LINE (inf,  line, line_length);
                PUT_LINE (outf, line (1..line_length);
            end loop;

            ...

        end copy_file;

Notes:


Template

The following pattern is common to all code that reads a file one line at a time:

Using the template

You can use the above template to write your file processing code:

  1. Decide what (if anything) needs to be done before any of the file is read.
  2. Decide what needs to be done to process a line that has been read in.
  3. Decide what final processing needs to be done (if anything) once the end of data is reached.

The previous example can be understood in this way.

They don't have to be lines of arbitrary characters. Another example shows that the code still fits into this pattern if lines are treated as containing integers. The important thing is that the whole line is treated as a unit.


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