File I/O
Principles
- Just as Turing identifies GUI widgets by integer ID number, Turing identifies files by integer ID number.
- The
open
command instructs the computer to connect to a file and assign an ID number. If the computer is unable to connect to the file, it assigns a negative ID number. - Programmers are obliged to check the connection every time they use the
open
command. If an error occurs, the message provided to the user should provide all of the information known about the error. - Files can be opened with one or more of the following capabilities:
get
,put
,read
,write
,seek
,mod
. - As soon as practicable after opening a file, it should be closed with the
close
command. There is a limit of around 20 open files, and “to avoid exceeding this limit, a program that uses many files one after another should close files that are no longer in use” (Turing online reference manual).
Example 1: Hard-coded file name
const FILE := "data.text" var inputFile : int var inputLine : string open : inputFile, FILE, get if inputFile < 0 then put "*** Yikes! Could not open \"", FILE, "\"." % take appropriate action (see discussion below) end if get : inputFile, inputLine
Error recovery
Whenever the open
command is used, there must be a sensible plan for recovery from a possible error. One possibility is to allow the user to correct the error; another is to gracefully terminate execution.
Example 2: User-provided file name
var fileName : string var inputFile : int loop put "File to be opened? " .. get fileName : * open : inputFile, fileName, get exit when inputFile > 0 put "*** Yikes! Could not connect to \"", fileName, "\"." put " Please enter the correct file name.", skip end loop
Not every file I/O program gathers a file name from the user; example 1 above uses a hard-coded file name. In some cases, it may be necessary to terminate execution of the subprogram (or main program) which fails to connect to a file.
Example 3: Early termination of a subprogram
procedure writeScoreToFile (score : int, scoreFile : string) var outputFile : int open : outputFile, scoreFile, put if outputFile < 0 then put "Error: was unable to write score to \"", scoreFile, "\"." return end if put : outputFile, score close : outputFile end writeScoreToFile writeScoreToFile (100, "score.text")
touque.ca > Education Commons > Turing
[This page last updated 2020-12-23 at 12h13 Toronto local time.]
© 2007–2024 Hersch, Bear & Company Limited. All rights reserved. “Grammar Authority,” “grammarauthority.com,” “touque.ca,” and “Canada’s Thinking Cap” are trademarks of Hersch, Bear & Company Limited. All other trademarks and copyrights are the property of their respective owners.
Privacy Policy | Licence to Copy | How to cite | Contact us