CSC 288 · Structured Programming
Our notes
2 min readRecords
type
Student = record
matric: string[12];
name: string[30];
level: integer;
cgpa: real
end;
var s: Student;
Fields are reached with a dot: s.cgpa := 4.21. The with statement shortens repeated access: with s do writeln(name, ' ', cgpa:0:2).
An array of records holds a whole class: class: array[1..200] of Student.
Text files
var f: text;
assign(f, 'scores.txt');
reset(f); { open for reading }
while not eof(f) do
begin
readln(f, name, score);
...
end;
close(f);
rewrite(f) creates a file for writing (erasing any old one); append(f) adds to the end (Turbo and Free Pascal).
Typed (binary) files
var sf: file of Student;
Records are stored in binary, all the same size, so a program can jump to record k with seek(sf, k) (counting from 0) and use filesize(sf). This is a simple direct-access file, the idea from file structures (CSC 283).
Worked example: class report from a file
A text file has one line per student: a score, a space, then the name. The program reads each line, counts the students, totals the scores and keeps the top scorer. For the lines
62 Ada
75 Bayo
58 Chika
the report is: 3 students, average 65.00, top: Bayo with 75.
(Reading the number first lets readln take the rest of the line as the name.)
Errors with files
With I/O checking off ({$I-}), a program can test ioresult after reset to see whether the file exists, and give a friendly message instead of crashing:
{$I-} reset(f); {$I+}
if ioresult <> 0 then writeln('File not found');
Exams usually ask
- Declare a record type and process an array of records.
- Write a program that reads a text file and produces a report.
- Distinguish text files from typed files.
Common mistake
Calling rewrite on a file you meant to read. rewrite empties the file at once; use reset to read.
Written by the UniHive team in our own words. Spotted a mistake? Tell us on WhatsApp.
No reading links here yet
Our team adds free books, videos and practice for each topic, and opens every link before it goes up.