Binary_reading

Hello!
I need help with the function for reading the binary file. I’m using

function read_bin(filename, dims::N) where N<:Integer
    stream = open(filename, "r");
    data = read(stream, Float16, dims);
    close(stream);
    return data
end

but this is giving error that I can not solve. Can someone help me?

There are couple options, I think the most straight forward one is this:

function read_bin(filename, dims::N) where N<:Integer
    # initial an array with known size
    data = Vector{Float16}(undef,dims)
    # or data = zeros(Float16,10)
    stream = open(filename, "r");
    # read stream into the pre-allocated typed-vector
    read!(stream, data);
    close(stream);
    return data
end

It looks like you are new to Julia, Welcome, you can ask this is kinda general question in First Step https://discourse.julialang.org/c/user/first-steps. You will get lots of help from there.

Even more compactly:

read_bin(filename, dims) = read!(filename, Vector{Float16}(undef, dims))

Argument-type declarations aren’t necessary, but if you want them for clarity I would suggest read_bin(filename::AbstractString, dims::Integer) (no where clause` is needed).

Note that the above code is endian-dependent; you could use ntoh or similar on the result to convert endianness if needed, or use a portable file format like HDF5.

1 Like