NASutils Knowledge BaseUnofficialPolski

BASIC · lesson 20 of 30 · Files and errorsHandle a missing file

if open(...) answers 1 or 0 instead of stopping the program. peek$("error") gives the reason.

Programming on the NAS › BASIC in 30 lessons

20-file-errors.yab Download 20-file-errors.yab

rem open(...) as a question: 1 when the file is open, 0 when it is not
name$ = peek$("argument")
if not open(1, name$, "r") then
  print "Cannot open ", name$
  print "Reason: ", peek$("error")
  exit 1
endif

lines = 0
while not eof(1)
  line input #1 line$
  lines = lines + 1
wend
close #1
print name$, " has ", lines, " lines"

Terminal

$ yabasic 20-file-errors.yab words.txt
words.txt has 3 lines
$ yabasic 20-file-errors.yab missing.txt; echo "exit code $?"
Cannot open missing.txt
Reason: could not open 'missing.txt': No such file or directory
exit code 1

Exercise

Try a second file name when the first one is missing.