Read/Write a binary file

From Cuis CookBook
Jump to navigation Jump to search

CAVEAT. This recipe was cooked in Linux and uses the file /dev/urandom which will be present in all Unix-like systems as far as the author knows. So, Linux, Mac, BSD are all fine.

Sometimes your file contains stuff which is not intended to be interpreted as a sequence of characters. This can be the case, for example, if you are reading/writing some compressed data, some audio file, a big matrix, a picture etc.

Reading from a binary file

Problem. I want to have a quite good random number and I know than most Unix systems provide a file /dev/urandom where I can read as many as I want. Please see your operating system documentation of the file to know how it works. This is a classic example of a binary stream, when I read from /dev/urandom I am supposed to read byte per byte, e.g. it would make not much sense to try to read a line. Also, this example is nice because you are not supposed to read in all the file, since this file has no end! You must read only a certain amount of it.

Solution. Follow the sequence of commands below to see how you can read from /dev/urandom as a binary stream.

"Make a ReadStream from a file"
rs _ '/dev/urandom' asFileEntry readStream. 
rs class.       "=> StandardFileStream "

" generally you may want to read a binary stream as a sequence of bytes."
rs useBytes . 

" get the fisrt byte"
rs next.             "=> 7 "

"get the following 10 bytes"
tmp _ rs next: 10.    "=>  #[192 101 93 30 46 183 55 186 231 66] "
tmp class.            "=> ByteArray "

" get 'tmp' in hex format, spaces added for readability by hand "
tmp hex. " 'EF F6 F0 1A 78 14 C0 02 73 1C' "

" get 'tmp' as base64, will make it shorter "
tmp base64Encoded .    "=> '15vGaEu2IU1NAQ==' "

" let's see what comes back if we read in binary mode"
tmp2 _ rs next.        "=> 238 "
tmp2 class.            "=> SmallInteger "

" we may want to read the binary stream as characters "
rs useCharacters .
rs next: 10.           "=> ')Orý»¯Ê³' "

" when you finished remember to close the stream. "
rs close.

TODO: Writing a binary file

To remember here is that writeStream asks confirmation if the file already exists, to have no question asked use forceWriteStream.


Dr. Nicola Mingotti last updated this on 3-Sep-2021. Examples where run in Cuis-5.0-4815.image.