open file filename close file filename write data to file filename read from file filename for number or read from file filename until character
In order to write to or read from a file, the file must first be opened. Following is an example of the open command:
This command will open a file called "binary data" on a floppy disk named "My disk". If such a file doesn't already exist HyperCard will create it. If HyperCard has problems opening the file it will put an error message into the variable result. Whenever you try to open a file you should test whether the variable result is empty. If so, then the open was successful. If not, you should print the error message and stop the program. For example:
on myHandler open file "My disk:binary data" if the result is not empty then -- error opening file: -- display the error message and leave this handler answer the result with "okay" else -- file opened successfully: -- what follows is the rest of the script for myHandler ... close file "My disk:binary data" end if end myHandler(Note that the name myHandler is just an example name. Select names for your handlers that describe the function they perform.)
You should always close any open files before the end of your script. If you fail to do this, other handlers will not be able to read from or write to the file. If you fail to do this, other handlers will not be able to read from or write to the file. An example:
This command will close the file "My disk:binary data".
This command will write the contents of the field "binary field" to the named file.
This command will write the Xth word of the Yth line of the card field to the file "My disk:binary data". Note that a blank has been explicitly added to separate words in the data file.
There are two general forms of the read command:
This is appropriate if you want to read the whole file at once, or if you know exactly how many characters you want to have read at a time. For example:
This command will read the next 50 characters from the named file (or the whole file, if there are fewer than 50 characters remaining) and puts the characters into the variable it.
This form of the command is appropriate when you want to read a chunk of data a time, such as a word, item or line. You can also read everything from the file up until any character desired. Note that the character used to read to is included in the data read from the file. Two examples follow:
This command will read the next line of data from the named data file. The line of data is put into the variable it.
This command will read the next word of data from the named data file. The word of data is put into the variable it.
on fileExample put "My disk:binary data" into extfile open file extfile if the result is empty then write card field X to file extfile close file extfile end if end fileExample