LearnStanmorephysics

Grade 11 · Powering Up

Text files

Grade 11 · Own methods & text files · Lesson and coding task · about 18 minutes

Open this task in the Delphi workspace →

Programs forget everything when they close — text files are how they remember. The reading ritual, always the same five steps:

AssignFile(tF, 'learners.txt');   // 1. connect the variable to the file
Reset(tF);                        // 2. open for READING
while not EOF(tF) do              // 3. while there are lines left
begin
  ReadLn(tF, sLine);              // 4. read one line
  // … use sLine …
end;
CloseFile(tF);                    // 5. always close!

Writing swaps step 2: Rewrite(tF) creates a fresh file (wiping any old one), Append(tF) adds to the end. Then WriteLn(tF, sLine); writes lines.

Each line here holds a name and mark joined by a semicolon — Thabo;78 — so your Grade 11 string skills split it:

iPos  := Pos(';', sLine);
sName := Copy(sLine, 1, iPos - 1);
iMark := StrToInt(Copy(sLine, iPos + 1, 4));

The files panel under the form preview shows the virtual files — watch summary.txt appear when your code runs.

What you will do

Hints
  1. First loop: AssignFile, Reset, while not EOF … ReadLn … CloseFile.
  2. Split with iPos := Pos(';', sLine); the name is Copy(sLine, 1, iPos - 1), the mark starts at iPos + 1.
  3. After the reading loop: AssignFile to summary.txt, Rewrite, two WriteLn lines, CloseFile.
Model solution
procedure TfrmFiles.btnProcessClick(Sender: TObject);
var
  tF : TextFile;
  sLine, sName : String;
  iPos, iMark, iCount, iPassed : Integer;
begin
  iCount := 0;
  iPassed := 0;
  AssignFile(tF, 'learners.txt');
  Reset(tF);
  while not EOF(tF) do
  begin
    ReadLn(tF, sLine);
    iPos := Pos(';', sLine);
    sName := Copy(sLine, 1, iPos - 1);
    iMark := StrToInt(Copy(sLine, iPos + 1, 4));
    memOutput.Lines.Add(sName + ' scored ' + IntToStr(iMark));
    Inc(iCount);
    if iMark >= 50 then
      Inc(iPassed);
  end;
  CloseFile(tF);

  AssignFile(tF, 'summary.txt');
  Rewrite(tF);
  WriteLn(tF, 'Learners: ' + IntToStr(iCount));
  WriteLn(tF, 'Passed: ' + IntToStr(iPassed));
  CloseFile(tF);
end;

About this material

This platform provides original CAPS-aligned practice material and study tools. Content is machine-verified and has not been reviewed by subject specialists. It is not affiliated with or endorsed by the Department of Basic Education. Learners should also use official past papers and consult their teachers where uncertain.