Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 36 ยท Projects and Practice

Project: Contact Book

Build a contact book in Pascal that stores records, searches, sorts and saves to a typed file, then run the same design as a complete C program in your browser.

Time to put the pieces together. This project builds a small contact book: you can add people, list them sorted by name, search by part of a name, remove an entry, and save everything to disk. It uses records, arrays, units, a typed file and the error handling from earlier lessons.

You write this project in Delphi or Free Pascal on your own machine. The browser cannot compile Pascal, so the Pascal code below is read-only, and the same design is given as a complete, runnable C program so you can watch the logic work and experiment with it.

What we are building

Features:

  1. Add a contact (name, phone, email).
  2. List all contacts, sorted by name.
  3. Find contacts whose name contains some text, ignoring case.
  4. Remove a contact by name.
  5. Save and Load the whole book from a file.

The design has three layers. Keeping them apart is the lesson of the project.

flowchart TD
  UI["Program: menu and input"] --> BOOK["Contacts unit: add, find, sort, remove"]
  BOOK --> STORE["Storage unit: save and load"]

The program talks to the contacts unit; only the storage unit knows about files.

The Contacts unit

First the data. A record per contact with fixed-size strings so it can go straight into a typed file (see typed files and streams):

PASCAL
unit Contacts;

interface

const
  MaxContacts = 100;

type
  TContact = record
    Name:  string[40];
    Phone: string[20];
    Email: string[60];
  end;

  TContactBook = record
    Items: array[1..MaxContacts] of TContact;
    Count: Integer;
  end;

procedure Clear(var Book: TContactBook);
function  Add(var Book: TContactBook; const C: TContact): Boolean;
function  IndexOfName(const Book: TContactBook; const Name: string): Integer;
function  Remove(var Book: TContactBook; const Name: string): Boolean;
procedure SortByName(var Book: TContactBook);
function  Matches(const C: TContact; const Part: string): Boolean;

implementation

uses
  System.SysUtils;

procedure Clear(var Book: TContactBook);
begin
  Book.Count := 0;
end;

function Add(var Book: TContactBook; const C: TContact): Boolean;
begin
  Result := (Book.Count < MaxContacts) and (IndexOfName(Book, C.Name) = 0);
  if Result then
  begin
    Inc(Book.Count);
    Book.Items[Book.Count] := C;
  end;
end;

function IndexOfName(const Book: TContactBook; const Name: string): Integer;
var
  I: Integer;
begin
  for I := 1 to Book.Count do
    if SameText(Book.Items[I].Name, Name) then
      Exit(I);
  Result := 0;             // 0 means "not found"
end;

function Remove(var Book: TContactBook; const Name: string): Boolean;
var
  I, At: Integer;
begin
  At := IndexOfName(Book, Name);
  Result := At > 0;
  if Result then
  begin
    for I := At to Book.Count - 1 do
      Book.Items[I] := Book.Items[I + 1];   // close the gap
    Dec(Book.Count);
  end;
end;

procedure SortByName(var Book: TContactBook);
var
  I, J: Integer;
  Tmp: TContact;
begin
  for I := 2 to Book.Count do                // insertion sort
  begin
    Tmp := Book.Items[I];
    J := I - 1;
    while (J >= 1) and (CompareText(Book.Items[J].Name, Tmp.Name) > 0) do
    begin
      Book.Items[J + 1] := Book.Items[J];
      Dec(J);
    end;
    Book.Items[J + 1] := Tmp;
  end;
end;

function Matches(const C: TContact; const Part: string): Boolean;
begin
  Result := Pos(LowerCase(Part), LowerCase(C.Name)) > 0;
end;

end.

A few design choices worth noticing:

  • Add returns False instead of raising when the book is full or the name exists, so the caller decides how to react. Returning a result is good for expected conditions; keep exceptions for the unexpected.
  • IndexOfName returns 0 for "not found", which is natural because indexes start at 1. In a zero-based design you would use -1.
  • Case-insensitive comparison uses SameText and CompareText, so "ada" and "Ada" are one person.
  • Remove shifts later entries down. That is fine for 100 entries; for large data you would use a TList or a database.

The Storage unit

Saving is a few lines because a typed file writes records directly:

PASCAL
unit Storage;

interface

uses
  Contacts;

procedure Save(const Book: TContactBook; const FileName: string);
procedure Load(var Book: TContactBook; const FileName: string);

implementation

procedure Save(const Book: TContactBook; const FileName: string);
var
  F: file of TContact;
  I: Integer;
begin
  AssignFile(F, FileName);
  Rewrite(F);
  try
    for I := 1 to Book.Count do
      Write(F, Book.Items[I]);
  finally
    CloseFile(F);
  end;
end;

procedure Load(var Book: TContactBook; const FileName: string);
var
  F: file of TContact;
  C: TContact;
begin
  Clear(Book);
  if not FileExists(FileName) then
    Exit;                       // first run: nothing saved yet
  AssignFile(F, FileName);
  Reset(F);
  try
    while (not Eof(F)) and (Book.Count < MaxContacts) do
    begin
      Read(F, C);
      Inc(Book.Count);
      Book.Items[Book.Count] := C;
    end;
  finally
    CloseFile(F);
  end;
end;

end.

The program (the menu loop) then needs only uses Contacts, Storage; and a repeat ... until that reads a command and calls these routines. Because the logic sits in units, you could later put a VCL form on top without touching it (see VCL forms and components).

The same design in C

Here is the whole thing as one runnable program. Section comments mark the "units". It scripts a session instead of reading the keyboard, so the output is deterministic, and it saves to a binary file and reloads it to prove the storage layer works.

C Contact book: add, sort, search, remove, save and load

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Extending the project

Try these in order; each adds one new skill:

  1. Edit a contact (Update) and refuse a rename that clashes with another name.
  2. Replace the array with TList<TContact> or TObjectList<TContactRecord>, and remove the 100-entry limit (see generics and anonymous methods).
  3. Use a TStringList to export a CSV file the user can open in a spreadsheet.
  4. Add a class TContactBook with properties Count and Items[I], hiding the array (see classes and objects).
  5. Store to SQLite with FireDAC (databases with FireDAC).
  6. Build the UI: a TListView and an edit panel in a VCL form.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the Contact record use string[40] instead of string?

    A typed file needs fixed-size records, and a normal string is only a reference to text elsewhere.
  2. 2. Why does Add return a Boolean instead of raising an exception when the name exists?

    Use return values for expected outcomes and exceptions for unexpected failures.
  3. 3. What is the benefit of separating the Contacts and Storage units?

    Layers with clear responsibilities are easier to test, replace and reuse.
  4. 4. What happens if Load is called on the first run when no file exists?

    The guard if not FileExists(...) then Exit makes the first run quiet and safe.

Summary

  • A contact book combines records, arrays, sorting, searching and a typed file.
  • Split the code into units: data and logic, storage, and the program that talks to the user.
  • Return Boolean or an index for expected outcomes (not found, duplicate); keep exceptions for real failures.
  • Fixed-size record fields make the typed-file layer trivial.
  • Extend it step by step: lists, classes, CSV, a database and a form.

Next: Project: Bank Accounts