Input from File

We provide demonstration programs for reading integers from a file of integer and real numbers from 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 will be read;
  2. reset to open an existing file;
  3. read (for the typed file) or readln (for the textfile);
  4. closeFile.

Run program SaveIntegers (the first program in the preceding section) before trying program LoadIntegers

program ReadIntegers;
  {$APPTYPE CONSOLE}
uses
  SysUtils;
var
  AverageLondonRainfall : array[1 .. 12] of integer;
  Count : integer;
  RainFile : file of integer;
begin
  assignFile(RainFile, 'rain.dat');
  reset(RainFile);
  writeln('Reading integers from rain.dat');
  for Count := 1 to 12 do
    begin
      read(RainFile, AverageLondonRainfall[Count]);
    end;
  closeFile(RainFile);
  write('Average London rainfall (Jan to Dec, mm): ');
  for Count := 1 to 12 do
    begin
      write(AverageLondonRainfall[Count], ' ');
    end;
  writeln;
  readln;
end.

Run program SaveReals (the second program in the preceding section) before trying program LoadReals

program ReadReals;
  {$APPTYPE CONSOLE}
uses
  SysUtils;
var
  //Choose a safe upper bound for the array to allow for appended data.
  TemperatureReadings : array [0 .. 20] of real;
  Count, ValueNumber : integer;
  TFile : textFile;
begin
  assignFile(TFile, 'Temps.txt');
  reset(TFile);
  writeln('Reading real numbers from Temps.txt');
  ValueNumber := -1;
  while not eof(TFile) do
    begin
      inc(ValueNumber);
      readln(TFile, TemperatureReadings[ValueNumber]);
    end;
  closeFile(TFile);
  write('Temperature readings: ');
  for Count := 0 to ValueNumber do
    begin
      write(TemperatureReadings[Count] : 4 : 1, ' ');
    end;
  writeln;
  readln;
end.
Programming - a skill for life!

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