NASutils Knowledge BaseUnofficialPolski

Pascal · lesson 29 of 30 · Tools for the NAS · bonusBuild a notepad

A TStringList loads and saves the notes; case chooses add, list or delete.

Programming on the NAS › Pascal in 30 lessons

29-notepad.pas Download 29-notepad.pas

program Notepad;
{$mode objfpc}{$H+}
{ add TEXT, list, delete NUMBER. The notes are in notes.txt. }
uses
  SysUtils, Classes;
const
  FileName = 'notes.txt';
var
  Notes: TStringList;
  I, Number: Integer;
begin
  Notes := TStringList.Create;
  try
    if FileExists(FileName) then
      Notes.LoadFromFile(FileName);
    case ParamStr(1) of
      'add':
        begin
          if ParamStr(2) = '' then
          begin
            WriteLn('Nothing added: give a text');
            ExitCode := 1;
            Exit;
          end;
          Notes.Add(StringReplace(ParamStr(2), #10, ' ', [rfReplaceAll]));
          Notes.SaveToFile(FileName);
          WriteLn('Added note ', Notes.Count);
        end;
      'list':
        begin
          if Notes.Count = 0 then
            WriteLn('No notes');
          for I := 0 to Notes.Count - 1 do
            WriteLn(I + 1, '. ', Notes[I]);
        end;
      'delete':
        begin
          Number := StrToIntDef(ParamStr(2), 0);
          if (Number < 1) or (Number > Notes.Count) then
          begin
            WriteLn('There is no such note');
            ExitCode := 1;
            Exit;
          end;
          Notes.Delete(Number - 1);
          Notes.SaveToFile(FileName);
          WriteLn('Deleted note ', Number);
        end;
    else
      WriteLn('usage: add TEXT | list | delete NUMBER');
      ExitCode := 2;
    end;
  finally
    Notes.Free;
  end;
end.

Terminal

$ ./29-notepad add "Buy two disks"
Added note 1
$ ./29-notepad add "Check the backup"
Added note 2
$ ./29-notepad list
1. Buy two disks
2. Check the backup
$ ./29-notepad delete 1
Deleted note 1
$ ./29-notepad delete 9; echo "exit code $?"
There is no such note
exit code 1
$ ./29-notepad list
1. Check the backup

Exercise

Add a command find TEXT that shows matching notes.

How it works

  • A TStringList keeps the notes. LoadFromFile and SaveToFile read and write notes.txt.
  • ParamStr(1) is the command, and case runs add, list or delete.
  • StrToIntDef turns the second word into a number and gives 0 for any other text. The check then rejects it.
  • The block finally frees the list on every way out of the program.