Pascal: Save Pupil Records in a File

program save_pupils;
const max = 5;
type pupil_record = record
          name : array [1..20] of char;
          form : array[1..3] of char;;
          year_of_entry: integer;
        end;
        pupil_array = array [1..max] of pupil_record;
        pupil_data = file of pupil_record;

var   pupils : pupil_array;
        pupil_file : pupil_data;
        x : char;
        choice : integer;

procedure sort_data;
var i, j: integer;
      temp : pupil_record;
begin
  for i := 1 to max -1 do
    for j := i + 1 to max do
      if pupils[i].name > pupils[j].name then 
        begin
          temp := pupils[i];
          pupils[i] := pupils[j];
          pupils[j] := temp;
        end;
end;

procedure get_data;
var i : integer;
begin
  writeln ('Enter details of ', max, ' pupils, name, form and year of entry');
  for i:= 1 to max do
   with pupils[i] do
    begin
      writeln ('Enter name:');
      readln (name);
      writeln ('Enter form:');
      readln (form);
      writeln ('Enter year of entry:');
      readln (year_of_entry);
    end;
  sort_data;
end;

procedure show_data;
var i : integer;
begin
  writeln ('You entered:');
  for i:= 1 to max do
   with pupils[i] do
      writeln ('Name: ', name, ' Form: ', form, ' Year of entry: ', year_of_entry);
end;

procedure save_data;
var i : integer;
begin
  assign (pupil_file, 'pupils.dat');
  rewrite (pupil_file);
  for i:= 1 to max do
    write (pupil_file, pupils[i]);
  close (pupil_file);
end;

procedure retrieve_data;
var i : integer;
begin
  i := 0;
  assign (pupil_file, 'pupils.dat');
  reset (pupil_file);
  while not eof (pupil_file) do
    begin
      read (pupil_file, pupils[i]);
      inc (i);
    end;
  close (pupil_file);
end;


begin
  repeat 
    writeln ('Enter choice from these options:');
    repeat
      writeln ('1. Enter pupil data');
      writeln ('2. Show data');
      writeln ('3. Sort data');
      writeln ('4. Save data on file');
      writeln ('5. Read data from file');
      writeln ('6. Quit');
      readln (choice);
      if not choice in [1..6] then writeln ('Invalid character, try again');
    until choice in [1..6];
    case choice of 
      1: get_data;
      2: show_data;
      3: sort_data;
      4: save_data;
      5: retrieve_data;
      6: writeln;
    end;
  until choice = 6;
  readln (x);
end.

 

Back to questions