BASIC · lesson 29 of 30 · Tools for the NAS · bonusBuild a notepad
add, list and delete work on an array that load fills and save writes to notes.txt.
29-notepad.yab Download 29-notepad.yab
rem A notepad: add TEXT, list, delete NUMBER. The notes are in notes.txt.
file$ = "notes.txt"
dim note$(100)
count = 0
load()
command$ = peek$("argument")
switch command$
case "add"
text$ = peek$("argument")
if text$ = "" or count = 100 then
print "Nothing added: give a text, 100 notes at most"
exit 1
endif
count = count + 1
note$(count) = text$
save()
print "Added note ", count
break
case "list"
if count = 0 print "No notes"
for i = 1 to count
print i, ". ", note$(i)
next i
break
case "delete"
number = int(val(peek$("argument")))
if number < 1 or number > count then
print "There is no such note"
exit 1
endif
for i = number to count - 1
note$(i) = note$(i + 1)
next i
count = count - 1
save()
print "Deleted note ", number
break
default
print "usage: add TEXT | list | delete NUMBER"
exit 2
end switch
sub load()
if not open(1, file$, "r") return
while not eof(1) and count < 100
count = count + 1
line input #1 note$(count)
wend
close #1
end sub
sub save()
local i
open #1, file$, "w"
for i = 1 to count
print #1, note$(i)
next i
close #1
end sub
Terminal
$ yabasic 29-notepad.yab add "Buy two disks"
Added note 1
$ yabasic 29-notepad.yab add "Check the backup"
Added note 2
$ yabasic 29-notepad.yab list
1. Buy two disks
2. Check the backup
$ yabasic 29-notepad.yab delete 1
Deleted note 1
$ yabasic 29-notepad.yab delete 9; echo "exit code $?"
There is no such note
exit code 1
$ yabasic 29-notepad.yab list
1. Check the backup
$ cat notes.txt
Check the backupExercise
Add a command find TEXT that shows matching notes.
How it works
dim note$(100)makes room for 100 notes. The subloadreadsnotes.txtinto it; if the file is missing, the list stays empty.peek$("argument")takes the command, andswitchrunsadd,listordelete.deletechecks the number first. Then each later note moves up by one place andsavewrites the file again.- A wrong number ends with code 1 and an unknown command with code 2, so a script can tell them apart.