Pascal · lesson 19 of 30 · Files and errors · bonusWrite and read a file
AssignFile links a variable with a file name. Rewrite starts an empty file, Append adds to its end, Reset reads it and CloseFile closes it.
19-files.pas Download 19-files.pas
program Files;
{$mode objfpc}{$H+}
var
F: TextFile;
Line: string;
N: Integer;
begin
AssignFile(F, 'shopping.txt');
Rewrite(F);
WriteLn(F, 'two disks');
WriteLn(F, 'a network cable');
CloseFile(F);
Append(F);
WriteLn(F, 'a UPS');
CloseFile(F);
Reset(F);
N := 0;
while not Eof(F) do
begin
ReadLn(F, Line);
Inc(N);
WriteLn(N, '. ', Line);
end;
CloseFile(F);
end.
Terminal
$ ./19-files
1. two disks
2. a network cable
3. a UPS
$ cat shopping.txt
two disks
a network cable
a UPSExercise
Write ten numbers into a file and read back their sum.