Output to File

We provide first a demonstration program for writing integers to a file of integer and real numbers to a textfile. In each case we use four procedures:

  1. assignFile so that the file identifier is associated with the string of the filename that it will be saved as;
  2. rewrite to open a new file;
  3. write (for the typed file) or writeln (for the textfile);
  4. closeFile to close the file and save it.
program SaveIntegers;
  {$APPTYPE CONSOLE}
uses
  SysUtils;
const
  AverageLondonRainfall : array [1 .. 12] of integer =
                          (61, 36, 50, 42, 45, 46, 46, 44, 43, 73, 45, 59);
var
  Count : integer;
  RainFile : file of integer;
begin
  assignFile(RainFile, 'rain.dat');
  rewrite(RainFile);
  writeln('Writing integers to rain.dat');
  for Count := 1 to 12 do
    begin
      write(RainFile, AverageLondonRainfall[Count]);
    end;
  closeFile(RainFile);
  readln;
end.
program SaveReals;
  {$APPTYPE CONSOLE}
uses
  SysUtils;
const
  TemperatureReadings : array [0 .. 5] of real =
                        (70.0, 64.2, 59.9, 57.1, 55.0, 53.4);
var
  Count : integer;
  TFile : textFile;
begin
  assignFile(TFile, 'Temps.txt');
  rewrite(TFile);
  writeln('Writing real numbers to Temps.txt');
  for Count := 0 to 5 do
    begin
      writeln(TFile, TemperatureReadings[Count]);
    end;
  closeFile(TFile);
  readln;
end.

The next program demonstrates how to append a data item to an existing textfile. Run program SaveReals (above) before trying it.

program AppendText;
  {$APPTYPE CONSOLE}
uses
  SysUtils;
var
  Count : integer;
  TFile : textFile;
begin
  assignFile(TFile, 'Temps.txt');
  append(TFile);
  writeln('Writing real number to the end of Temps.txt');
  writeln(TFile, 18.2);
  closeFile(TFile);
  readln;
end.

The final program in this section demonstrates how to use random access to locate and edit a data item in a typed file. Run program SaveIntegers (the first program in this section) before trying it.

program EditInteger;
  {$APPTYPE CONSOLE}
uses
  SysUtils;
var
  MonthNo, Rainfall : integer;
  RainFile : file of integer;
begin
  assignFile(RainFile, 'rain.dat');
  reset(RainFile);
  write('For which month number would you like to enter new value? ');
  readln(MonthNo);
  write('Please enter the new average rainfall. ');
  readln(Rainfall);
  seek(Rainfile, MonthNo - 1); //Data item numbering starts at 0
  writeln('Entering new value');
  write(RainFile, Rainfall);
  closeFile(RainFile);
  readln;
end.

See the Printing section for demonstration programs that output rtf and csv files.

Programming - a skill for life!

Input from keyboard and file and output to monitor, file and printer