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
- Read learners.txt line by line with the EOF loop
- Split each line at the ; and add a memo line: Thabo scored 78
- Count the learners and how many passed (mark >= 50)
- Write summary.txt with two lines: Learners: 5 and Passed: 3
Hints
- First loop: AssignFile, Reset, while not EOF … ReadLn … CloseFile.
- Split with iPos := Pos(';', sLine); the name is Copy(sLine, 1, iPos - 1), the mark starts at iPos + 1.
- 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;