How do you read structures from a file?

There used to be a nice package called StrPack.jl for this sort of thing, but it stopped being maintained. But @Keno put together a replacement called StructIO.jl, although it doesn’t seem to have gotten a lot of attention in the last couple of years. StructIO is a registered package and its tests still pass, however, so it would be worth trying.

Also, it could give a cleaner API if you use StaticArrays.jl and StaticStrings.jl instead of tuples for the struct fields.

For example:

using StructIO, StaticStrings, StaticArrays

@io struct Frame
    s::StaticString{13}
    n::SVector{10, Int16}
    x::SVector{20, Float32}
end align_packed

which gives an on-disk size of 113 bytes:

julia> packed_sizeof(Frame)
113

Then you should be able to read from a file f with simply:

f = open("data.dat", "r")
data = [unpack(f, Frame) for i = 1:100]

@Keno, it would be nice if StructIO.jl could be transferred to JuliaIO and given a little TLC, especially more documentation.

2 Likes