Programmer Reference : Common File System : Using file streams : Opening and closing file streams
Opening and closing file streams
The open: and openEmpty: messages are the simplest means of opening a new file stream instance on a particular file. Both messages are sent to the file stream class representing the desired access mode. The open: message opens an existing file, while the openEmpty: message truncates an existing file (to size 0) or creates the file if it does not exist. Accordingly, the CfsReadFileStream class does not respond to the openEmpty: message.
Generally, open: is used when reading files and openEmpty: is used when writing new files or overwriting existing files. Some examples follow.
| file |
"Opens an existing file for reading and writing, creates the file if it
does not exist."
(file := CfsReadWriteFileStream open: 'existing.txt') isCfsError
ifTrue: [^self error: file message].
"...Use the file stream for reading and/or writing..."
file close.
| file |
"Opens an existing file for reading only, fails if it does not exist"
(file := CfsReadFileStream open: 'existing.txt') isCfsError
ifTrue: [^self error: file message].
"...Use the file stream for reading..."
file close. "When done, close the file stream, which closes the file."
| file |
"Opens a new file for writing only, truncates it to size 0 if it already exists."
(file := CfsWriteFileStream openEmpty: 'new.txt') isCfsError
ifTrue: [^self error: file message].
"...Use the file stream for writing..."
file close.
Once all desired operations have been performed, the file stream instance must be closed by sending it the close message before it is discarded. This closes the file, by deallocating any operating system resources associated with the file stream, and flushing any cached data to disk.
On double-byte platforms, the platform character encoding does not necessarily match the character encoding used within Smalltalk. As a result, Smalltalk strings must be converted to and from the platform representation as they are written to and read from files. When the Smalltalk and platform encodings differ, the stream answered by the open: and openEmpty: messages will not be an instance of the class to which the message was sent. In such cases the open: and openEmpty: messages answer a specialized stream that conforms to the requested protocols and manages the conversion of Smalltalk strings to the appropriate platform representation.
In these cases, it is important to use the isCfsError message to test the result of the open: and openEmpty: operations rather than testing the class of the returned object (for example, returnedObject class == CfsReadFileStream).
Last modified date: 01/29/2015