Text Files and the FileIO Xtra
August 1, 2000
by Gary Rosenzweig
This week, to celebrate (and shamelessly promote) my new book, I've decided to give you a useful excerpt from it. The new book is Special Edition Using Director 8 from QUE. It is primarily an update of my Special Edition Using Director 7 book, but I worked hard to add Director 8's new features to the book, improve each and every chapter, and add all sorts of new goodies.
This is the section from chapter 16 that deals with the FileIO Xtra. It gives two very useful handlers that allow you to deal with reading from and writing to text files. I think it is useful in its own right, as well as a good representation of the contents of the book. Hope you like it, and I hope you'll check out the book at your local bookseller or online. Check out http://clevermedia.com/resources/bookstore/book5.html for details and a table of contents.
Using text files has always been more difficult in Director than it should be. Director 8 is no different. It requires you to use the FileIO Xtra. This is an Xtra that adds Lingo commands to handle reading and writing files. Using an Xtra such as this is like using a behavior, except that the Xtra is referenced through a variable, not a sprite. Here is an example. To read a text file, use the following series of commands:
fileObj = new(xtra "FileIO")
openFile(fileObj, "myfile.txt", 1)
text = readfile(fileObj)
closeFile(fileObj)
The variable fileObj is used to store an instance of the Xtra. The new command in the first line creates this instance, and a pointer to it is placed in the variable fileObj. You can think of fileObj as the me in a behavior. It is now needed to refer to this instance of FileIO. An instance of FileIO is capable of opening, creating, writing, reading, and deleting files. In the preceding example, the object is used to open a file with the openFile command, read the contents of the file with the readFile command, and then close the file with the closeFile command. The 1 at the end of the openFile command signifies that the file is being opened for reading. A 2 would mean that it is opened for writing.
Here is a complete list of commands used with the FileIO Xtra:
new | Creates a new instance of the Xtra |
fileName | Returns the name of the file currently being controlled by this instance of the Xtra |
status | Returns the error code of the last command used on the Xtra. A 0 means that there was no error |
error | Takes the object and an integer as parameters. It returns a string with the description of the error number passed in as the integer |
setFilterMask | Takes the object and a string as parameters. The string defines the type of files to be shown in the Open and Save dialog boxes. On the Mac, pass a string that contains one or more four-letter file types, such as "TEXT" or "JPEGGIFF". In Windows, the string should be a comma-delimited list alternating file descriptions and types, such as "Text Files,*.txt,GIF Files,#.gif" |
openFile | Opens the file for reading, writing, or both. You need to call this function before performing most other file functions. It takes an additional parameter, which should be a 1 to read, a 2 to write, or a 0 for both |
closeFile | Closes the file associated with the file object. You must call this when you are finished with the file |
displayOpen | Displays a Mac or Windows Open dialog box and enables users to browse and select a file. It returns that file path |
displaySave | Displays a Mac or Windows Save dialog box and enables users to browse and select the destination of that file. It returns that file path |
createFile | Give this command the object and a string that represents the filename or full path of the file. You must call this before openFile in cases where the file does not yet exist |
setPosition | Takes an integer as an extra parameter. It sets the position in the file where the next read will take place |
getPosition | Returns the current reading position in the file |
getLength | Returns the length of the currently opened file |
writeChar | Writes a single character to the file |
writeString | Writes a complete string into the file |
readChar | Reads a single character from the file |
readLine | Reads from the current position in the file to the next return character. It includes the return character in the returned value |
readFile | FileReads from the current position in the file until the end |
readWord | Reads from the current position in the file until the next space or nonvisible character |
readToken | Takes three parameters: the object, a skip character, and a break character. It reads from the current position in the file until the break character, and it skips the skip characters whenever it encounters them |
getFinderInfo | Gets the file type and creator of the currently opened file. It returns it as a nine-character string with a space between the file type and creator. For example: "TEXT ttxt". Mac-only function |
setFinderInfo | Enables you to set the file type and creator of the currently open file. You must use a nine-character string, such as "TEXT ttxt". Mac-only command |
delete | Removes the currently opened file |
version | Returns the version of the Xtra. Use it in this manner: put version(xtra "FileIO") |
getOSDirectory | Part of the Xtra, but does not require a reference to it. Use it in this manner: put getOSDirectory(). It returns the path to the Mac system folder or the Windows directory |
Reading and writing files takes many lines of code. However, a handler that does this can be reused many times. Here is a handler that prompts users for a text file to read, and then returns that text file's contents:
on openAndReadText
-- create the FileIO instance
fileObj = new(xtra "FileIO")
-- set the filter mask to text files
if the platform contains "mac" then
setFilterMask(fileObj,"TEXT")
else
setFilterMask(fileObj,"Text Files,*.txt,All Files,*.*")
end if
-- open dialog box
filename = displayOpen(fileObj)
-- check to see if cancel was hit
if filename = "" then return ""
-- open the file
openFile(fileObj,filename,1)
-- check to see if file opened ok
if status(fileObj) <> 0 then
err = error(fileObj,status(fileObj))
alert "Error:"&&err
return ""
end if
-- read the file
text = readFile(fileObj)
-- close the file
closeFile(fileObj)
--return the text
return text
end
If you want to use this handler to read a file that you already know the name of, just pass in the filename variable as a parameter to the handler, and remove the references to the setFilterMask and displayOpen commands. The opposite of this handler is one that saves any text to a file. This handler takes care of it all, down to setting the file type of the new file to a SimpleText file for the Mac. The text placed in the file is passed in as a parameter. Oddly, when writing out a new file, you must first open the file, and then use the delete command to delete it. Then, you can use createFile and openFile to create and write a new file. If you do not do this, the new file overwrites any file of the same name that already exists, and there might be some parts of the old file left in the new one.
on saveText text
-- create the FileIO instance
fileObj = new(xtra "FileIO")
-- set the filter mask to text files
if the platform contains "mac" then
setFilterMask(fileObj,"TEXT")
else
setFilterMask(fileObj,"Text Files,*.txt,All Files,*.*")
end if
-- save dialog box
filename = displaySave(fileObj,"","")
-- check to see if cancel was hit
if filename = "" then return FALSE
-- delete existing file, if any
openFile (fileObj,filename,2)
delete(fileObj)
-- create and open the file
createFile(fileObj,filename)
openFile(fileObj,filename,2)
-- check to see if file opened ok
if status(fileObj) <> 0 then
err = error(fileObj,status(fileObj))
alert "Error:"&&err
return FALSE
end if
-- write the file
writeString(fileObj,text)
-- set the file type
if the platform contains "Mac" then
setFinderInfo(fileObj, "TEXT ttxt")
end if
-- close the file
closeFile(fileObj)
return TRUE
end
The on saveText and on openAndReadText handlers can be customized in many ways to suit many purposes. You can use getOSDirectory(), for instance, to find the path to the operating system and store files in the preferences folder. You can also use the Lingo property the pathname to get the path of the Director application or Projector to store files there.
Gary Rosenzweig's new book "Special Edition Using Director 8" is now available. It's the most comprehensive guide to Director ever, including tons of examples and demo movies. It's suitable for novices and experts alike. More information about the book can be found at http://clevermedia.com/resources/bookstore/book5.html. It can be purchased there, or in your local bookstore.
Copyright 1997-2024, Director Online. Article content copyright by respective authors.