BinaryStream objects are used to read and write data to and from a binary file. The benefit of using BinaryStreams rather than text streams is that you can read from and write to any position in the file. Text files must be read sequentially from the start to the end.
The following class constants can be used to specify the value of the Type parameter of the Handle property.
|HandleTypeFileNumber||A file descriptor|
|HandleTypeFilePointer||A file pointer|
|HandleTypeMacFileRefNum||A File reference number|
|HandleTypeWin32Handle||A Windows32 OS handle|
When the BinaryStream goes out of scope, it is flushed and closed.
What is the LittleEndian property? The Windows and Linux operating systems store binary values in the reverse order from the Mac OS PowerPC machines. If you were using the ReadInt16 or ReadIn32 methods to read data from a file that was in Little Endian format, you would get incorrect data. Data is read in Big Endian format by default. Most Macintosh files are in Big Endian format. If you are reading a file that is in Little Endian format, you will need to set the Little Endian property to True before you begin reading the file. This applies to writing data with WriteInt16 and WriteInt32.
For example, in big endian (like the Mac OS), the value 258 would be stored as:
while in Little Endian, it would be stored as:
If the LittleEndian property is set incorrectly, then you would read the value as 513.
You can use the LittleEndian property to write your code to be OS-independent. Set the LittleEndian property to True if the file format is intrinsically little endian (i.e. GIF files), otherwise leave it as False.
This example reads each pair of bytes from a file and writes them in reverse order to a new file. The user chooses the source file using the Open-file dialog box and saves the new file using the Save as dialog box.
If readFile <> Nil And readFile.Exists Then
Dim ReadStream As BinaryStream = BinaryStream.Open(readFile, False)
ReadStream.LittleEndian = True
Dim WriteFile as FolderItem = GetSaveFolderItem("", "")
If writeFile <> Nil Then
Dim writeStream As BinaryStream = BinaryStream.Create(writeFile, True)
writeStream.LittleEndian = True
Do Until ReadStream.EOF
This example displays the Save As dialog box and writes the contents of the TextArea to a text file.
Dim stream As BinaryStream
f = GetSaveFolderItem(FileTypes1.Text, "Untitled.txt")
If f <> Nil Then
stream = BinaryStream.Create(f, True) // Overwrite if exists
Check the individual properties and methods for more examples.