Reading and writing data
Data can be transferred between a file and a buffer by sending the read:startingAt:nbyte: and write:startingAt:nbyte: messages to the CfsFileDescriptor instance returned by the open:oflag: message. The first argument specifies the buffer, which can be either a String or ByteArray instance. The second argument specifies the position in the buffer to or from which data is to be transferred. The third argument specifies the number of bytes to be transferred. The messages answer the number of bytes that were successfully read or written.
The startingAt parameter refers to the position in the buffer, not in the file. To change the position in the file (the file offset) use the lseek:whence: message.
"Example of read/write: low level file copy using buffers"
| source target buf bytesRead bufSize |
(source := CfsFileDescriptor
open: 'example.txt'
oflag: ORDONLY) isCfsError
ifTrue: [^self error: source message].
(target := CfsFileDescriptor
open: 'example.bak'
oflag: OWRONLY | OCREAT | OTRUNC) isCfsError
ifTrue: [^self error: target message].
"Choose a reasonable size"
bufSize := 4096.
"Could also use a ByteArray"
buf := String new: bufSize.
(bytesRead := source read: buf startingAt: 1 nbyte: bufSize) > 0]
whileTrue: [
bytesRead > (target write: buf startingAt: 1 nbyte: bytesRead)
ifTrue: [
"Fewer bytes written than requested - might indicate full
file system"
source close.
target close.
^self error: 'Unable to copy file. File system could be full.']].
source close.
target close.
There is no need to implement a low-level file copy function. CfsFileDescriptor CfsFileDescriptorclass>>#copy:new: portably provides this functionality using the most efficient means for each platform.
Last modified date: 01/29/2015