writing uint16's to a binary file
Bijan Parsia
bparsia at email.unc.edu
Mon Mar 11 18:23:11 UTC 2002
On Mon, 11 Mar 2002, Ken G. Brown wrote:
> I'm needing to write a bunch of lines of uint16's to a binary file. So far I
> have a variation of the following but it gives a message not understood,
> adaptToNumber:andSend:.
Er..I found this to be rather confusing code (and I don't have uin16 in my
image). Some comments.
> test _ #(1 2 3 4 5 6 7 8).
> rStr _ ReadStream on: test.
WHy the ReadStream?
> outfile _ fileStream _ (FileStream newFileNamed: 'outfile') binary.
Why the double assignment?
> outfile nextPutAll: (rStr do: [ :ii | rStr uint16]).
This is definitely broken in a couple of places, most notable in the
block. Surely you want ii uint16? Second, if uint16 *returns* something,
rather than modifying the receiver (which I suspect will be the case) then
you won't have "done" anything that outfile will see. (I'm a bit
suspicious about nextPutAll:ing a stream anyway).
Perhaps
outfile nextPutAll: (test collect: [:ii | ii uint16]).
(Collect returns the collection of the results of the block as applied to
the receiver's elements.) So the more intelligible to me, although perhaps
incorrect, version is:
test _ #(1 2 3 4 5 6 7 8).
outfile _ (FileStream newFileNamed: 'outfile') binary.
outfile nextPutAll: (test collect: [ :ii | rStr uint16]).
outfile close.
However, you may consider using some of the "nonhomogeneous
access" methods from PositionableStream, e.g., #nextInt32Put:,
#nextNumber:put: and friends. In that case, you may put that inside the
loop:
test _ #(1 2 3 4 5 6 7 8).
outfile _ (FileStream newFileNamed: 'outfile') binary.
test do: [:ii | outfile nextIn32Put: ii].
outfile close.
Finally, it's often a good idea to use an #ensure: to make sure your file
closes (in a timely fashion...finalization will catch it eventuallly) even
if you get an error. Something like:
[test do: [:ii | outfile nextInt32Put: ii]]
ensure: [outfile close].
Cheers,
Bijan Parsia.
More information about the Squeak-dev
mailing list
|