How to create and read binary files in Julia

A binary file consists of a sequence of eight-bit bytes that are sequentially arranged in a binary format. There are two types of binary files: encrypted and text files. However, binary file types span over a broad spectrum of categories like executables, graphics, libraries, databases, archives, etc.

Binary files are not human-readable, and in order to interpret their content, a special program or processor must know in advance how this content is formatted and how to read it.

Let's go through the following examples to discover first how to create a binary file and then how to read its respective content in Julia's ecosystem:

Code example 1

This example shows how to create a binary file while using the command write:

The syntax of this command is as follows:

n = write(filename,x)
Syntax

This command accepts two parameters:

  • filename: This represents the path of the binary file to be created.

  • x: This represents the canonical binary representation of the value to be written.

It returns the number of bytes written.

input = rand(Float32, 2, 2)
print("\ninput = ", input)
bytes = write("/usercode/output/file.bin", input)
print("\nNumber of bytes written = ", bytes)

Code explanation

Let's now dig into the code widget above:

  • Line 1: We generate a 2-D array of random float values and store the result in the variable input.

  • Line 2: We print out the content of the variable input.

  • Line 3: We create a binary file including the content of the variable input.

  • Line 4: We print out the number of bytes written.

Code example 2

This example shows how to read a binary file while using the command read!:

The syntax of this command is as follows:

read!(filename,x)
Syntax

This command accepts two parameters:

  • filename: This represents the path of the binary file to be read.

  • x: This represents the array hosting the read binary data.

input = rand(Float32, 2, 2)
print("\ninput = ", input)
write("/usercode/output/file.bin", input)
output = Array{Float32}(undef, (2, 2))
open("/usercode/output/file.bin") do io
read!(io, output)
end
print("\noutput = ",output)
print("\nAssert input == output:",input == output)

Code explanation

Let's walk through the code widget above:

  • Line 5: We initialize a variable called output to an empty 2-D array of float values.

  • Lines 6–8: We open the binary file, read its content, and store the latter in a variable named output.

  • Line 9: We print out the content of the variable output.

  • Line 10: We print out a message asserting that input and output variables are equal.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved