Wednesday, July 13, 2016

Dictionary lookup - saving to disk

One advantage of using our single string dictionary lookup technique is that saving to and reading from a disk file is amazingly simple.  Just open the file and write the string.

sub writeDictionary
  open "dictionary.dat" for output as #writeDict
    print #writeDict, dictionary$
  close #writeDict
end sub

Reading on the other hand requires a slightly more sophisticated technique.  For example, if any of the keys or values have return characters in them then we want to make sure we read the whole file all the way to the end.  For this we will use the input$() function.

sub readDictionary
  open "dictionary.dat" for input as #readDict
  length = lof(#readDict)
  dictionary$ = input$(#readDict, length)
  close #readDict
end sub

The ability to preserve return characters is useful more for the values than for the keys, which for most applications will probably just be short one or two word names.