Binary files
Not every file is text. Pictures, archives and programs are bytes in a particular layout. This lesson writes and reads a tiny binary format, looks at its bytes with a hex dump, and learns the habits that protect against wrong files.
What you will learn#
- the difference between text and binary files,
FileStream,BinaryWriter,BinaryReader,- designing a small file format with a magic number,
- a hex dump,
- bytes, little endian and the type that you pass,
- closing files in every case.
Text and binary#
A text file is a list of characters (encoded as bytes). A binary file is a list of bytes with a meaning that only the format tells: the first four bytes are a number, the next ones a name... A program that does not know the format sees garbage. A binary format is smaller and faster to read, and exact (a number is stored as a number, not as the text 21.5).
The program#
# binary files - bytes, BinaryWriter and BinaryReader, a file format, and a hex dump
load "dotnet.ring"
using {
"System"
"System.IO"
"System.Text"
}
func main
cFile = new Path().Combine([new Path().GetTempPath(),"ringdotnet_binary.dat"])
# 1. A binary file stores values as bytes, not as readable text. We invent a tiny format:
# the text "RDN1" (a "magic number": it says what kind of file this is), then
# a 32-bit whole number (the count), a text (the title), and that many decimal numbers.
# Note: Write(21.5) writes a decimal number (8 bytes); Write(23) would write a whole number (4 bytes). The type that you pass decides.
oStream = new FileStream(cFile,"Create")
oWriter = new BinaryWriter(oStream)
oWriter.Write("RDN1")
oWriter.Write(3)
oWriter.Write("Temperatures")
oWriter.Write(21.5)
oWriter.Write(19.25)
oWriter.Write(23.75)
oWriter.Close()
? "1. Written: " + new FileInfo(cFile).Length + " bytes"
# 2. The raw bytes: a hex dump shows offset, bytes in hex, and the printable characters
? nl + "2. The hex dump of the file:"
? hexDump(cFile)
# 3. Read it back with a BinaryReader: the reads must follow the same order as the writes
oReader = new BinaryReader(new FileStream(cFile,"Open"))
cMagic = oReader.ReadString()
nCount = oReader.ReadInt32()
cTitle = oReader.ReadString()
? nl + "3. Magic '" + cMagic + "', " + nCount + " values, title '" + cTitle + "'"
for nIndex = 1 to nCount
? " value " + nIndex + " = " + oReader.ReadDouble()
next
oReader.Close()
# 4. Checking the magic number protects against opening the wrong kind of file
new File().WriteAllText([ :path = cFile, :contents = "just some text, not our format" ])
if readMagic(cFile) != "RDN1"
? nl + "4. Not our file format: refused"
ok
# 5. Bytes and numbers: BitConverter shows how a number is stored. Little endian: the smallest byte comes first
aBytes = new BitConverter().GetBytes(1000)
? nl + "5. 1000 as bytes: " + len(aBytes) + " bytes, the first two are " + ascii(aBytes[1]) + " and " + ascii(aBytes[2]) + " (1000 = 3 * 256 + 232)"
# 6. Reading into a BUFFER. Stream.Read(buffer, offset, count) writes into an array that you pass in, so it needs a live .NET array and not
# a Ring text (a text is copied on the way in). dnBuffer makes such an array; Read gives the number of bytes that it wrote, and
# dnBufferBytes copies them back into a Ring text. The file is the one of step 4, a text that starts with "just".
oStream = new FileStream(cFile,"Open")
oBuffer = dnBuffer(16)
nRead = oStream.Read(oBuffer,0,16)
oStream.Dispose()
? nl + "6. read " + nRead + " bytes into a buffer of " + dnBufferSize(oBuffer) + "; the first four are '" + dnBufferBytes(oBuffer,4) + "' (the text file of step 4)"
new File().Delete(cFile)
# a hex dump: 8 bytes per line
func hexDump cFile
cData = new File().ReadAllBytes(cFile)
cOut = ""
for nStart = 1 to len(cData) step 8
cHex = ""
cChars = ""
for nIndex = nStart to min(nStart + 7,len(cData))
nByte = ascii(cData[nIndex])
cHex += right("0" + hex(nByte),2) + " "
if nByte >= 32 and nByte < 127
cChars += cData[nIndex]
else
cChars += "."
ok
next
cOut += " " + right("0000" + hex(nStart - 1),4) + " " + cHex + copies(" ",8 - (min(nStart + 7,len(cData)) - nStart + 1)) + " " + cChars + nl
next
return cOut
func readMagic cFile
cMagic = ""
oReader = ""
try
oReader = new BinaryReader(new FileStream(cFile,"Open"))
cMagic = oReader.ReadString()
catch
cMagic = ""
done
# close the file in every case, also after an error: an open file can not be deleted
if isobject(oReader)
oReader.Close()
ok
return cMagic
func copies cText, nTimes
cResult = ""
for nIndex = 1 to nTimes
cResult += cText
next
return cResult1. Written: 46 bytes
2. The hex dump of the file:
0000 04 52 44 4e 31 03 00 00 .RDN1...
0008 00 0c 54 65 6d 70 65 72 ..Temper
0010 61 74 75 72 65 73 00 00 atures..
0018 00 00 00 80 35 40 00 00 ....5@..
0020 00 00 00 40 33 40 00 00 ...@3@..
0028 00 00 00 c0 37 40 ....7@
3. Magic 'RDN1', 3 values, title 'Temperatures'
value 1 = 21.50
value 2 = 19.25
value 3 = 23.75
4. Not our file format: refused
5. 1000 as bytes: 4 bytes, the first two are 232 and 3 (1000 = 3 * 256 + 232)
6. read 16 bytes into a buffer of 16; the first four are 'just' (the text file of step 4)How it works#
The format#
We invented it: first the text RDN1, then the count (3) as a 32-bit whole number, the title as a text, then that many decimal numbers. Any reader must follow exactly the same order. The BinaryWriter writes each value in a fixed, compact way, and the BinaryReader reads them back with matching calls: ReadString, ReadInt32, ReadDouble.
Reading the hex dump#
Each line of the dump shows an offset (position), eight bytes in hexadecimal, and the same bytes as characters (. for unprintable ones). Read the real file:
0000 04 52 44 4e 31 03 00 00 .RDN1...04is the length of the text that follows: aBinaryWriterwrites a text as length + characters:04then52 44 4e 31=R D N 1.03 00 00 00is the whole number 3 written in 4 bytes. The smallest byte comes first (little endian): that is how Windows computers store numbers. 1000 isE8 03 00 00: 1000 = 3 × 256 + 232 (E8), which step 5 shows withBitConverter.0c= 12, the length ofTemperatures.- The three decimal numbers take 8 bytes each (
00 00 00 00 00 80 35 40is 21.5).
The type that you pass decides#
Write(21.5) writes a decimal (8 bytes); Write(23) would write a whole number (4 bytes) because Ring numbers without decimals are passed as integers. If you then read it back with ReadDouble you get an error ("unable to read beyond the end"). When the reader and the writer disagree, the file is garbage. Keep the values of a decimal field decimal (23.0 is still whole to Ring: add a fraction or convert the value) and test your format by reading back what you wrote.
A buffer that .NET fills#
File.ReadAllBytes gives the whole file as a Ring text. For a big file, or for a network stream, a program reads in pieces with Stream.Read(buffer, offset, count): .NET writes into the array that you pass in, and returns how many bytes it wrote. A Ring text cannot be that array (it is copied when it goes in), so the program makes a byte buffer: dnBuffer(16) is a .NET object that holds a byte[] of 16 bytes, and every parameter of type byte[] receives the live array inside it. After the call dnBufferBytes(oBuffer, nRead) copies the first nRead bytes into a Ring text. The text can hold any byte, so nothing is lost. The same buffer is used with sockets and with the registry (the tutorial The Windows Registry).
The magic number#
The first bytes of a file say what kind of file it is: PNG files start with 89 50 4E 47, zip files with PK. A reader checks them first and refuses anything else. Step 4 writes a text file over our file and readMagic returns something that is not RDN1: refused, instead of reading nonsense.
Close files in every case#
The reader and writer hold the file open. An open file cannot be deleted or replaced, and its last bytes may not be written yet. readMagic closes the reader after the try / catch, so it is closed also when reading failed. (The first version of this tutorial closed it inside try: the failed read left the file open and the final Delete failed. That is exactly the kind of mistake to look for.)
What you learned#
- binary files are bytes with a format,
BinaryWriter/BinaryReaderread and write in the same order,- a hex dump shows the truth,
- little endian,
- magic numbers,
- always close.
Exercises#
- Add a version number to the format, and make the reader accept versions 1 and 2.
- Write a list of names (count, then each name) and read it back.
- Extend
hexDumpto take a start offset and a length. - Read the first 8 bytes of a PNG file and check that they are
89 50 4E 47 0D 0A 1A 0A.