Reading binary values from a file

Hi Peter, why do we need stream = ..., in:

stream = open(filename, "r") do stream ... ?

Also, shouldn’t it be: 4*index - 4, in:

readvalue(stream, 4*index - 3) ?

See a working example here:

function readvalue(stream, position)
    seek(stream, position)
    return read(stream, Int32)
end

function readvalues(filename::AbstractString, indices)
    open(filename, "r") do stream
        return [readvalue(stream, 4*index-4) for index in indices]
    end
end

# Writing test file:
x = Int32.(1:1000)
open("array_Int32.bin", "w") do io
    write(io, x, Int32[])
end

# Reading test file:
y = readvalues("array_Int32.bin", 1:10:1000)

Thanks.

1 Like