Back to DFS's Pascal Page


FILES I - Integers as Text

The programs below process integer data, making use of text files.

Program writenum creates a file called nums.dat and writes the even numbers from 2 to 10 into it. Each number is followed by hexadecimal 0D 0A. The resulting file will look like the following:

Hex 32 0D 0A 34 0D 0A 36 0D 0A 38 0D 0A 31 30 0D 0A
ASCII 2 CR LF 4 CR LF 6 CR LF 8 CR LF 1 0 CR LF

Program readnum opens a file called nums.dat, reads the integer values found there, and stores the values in an array.

program writenum;
{Writing integers to a text file}
var
  outfile: Text;
  i : integer;
begin
  Assign(outfile, 'nums.dat');
  Rewrite(outfile);
  for i := 1 to 5 do
     writeln(outfile, i * 2);
  Close(outfile)
end.

program readnum;
{Reading integers from a text file into an array}
const
  Max = 20;
var
  infile: Text;
  nums : array [1..Max] of integer;
  i, numnums : integer;
  err : integer; {error for val()}
  numstr : string; {input buffer}
  tempnum : integer; {temporary storage}
begin
  Assign(infile, 'nums.dat');
  Reset(infile);
  numnums := 0;
  while (not (EOF(infile))) do
    begin
      readln(infile, numstr);
      val(numstr, tempnum, err);
      if( err = 0) then
        begin
          numnums := numnums + 1;
          nums[numnums] := tempnum;
        end;
    end;
  Close(infile)
end.

© 1999 DFStermole
HTMLified: 29 Dec 99