[erlang-questions] read_file -- binary data object

Joe Armstrong erlang@REDACTED
Thu Dec 20 10:49:40 CET 2018


A binary is just an area of memory containing raw bytes.

L = binary_to_list(B) converts the binary B into a list of integers L where
each integer is in the range 0..255

list_to_binary(L) is the inverse.

A list of small integers of length N takes 16*N bytes of storage (on a
64 bit word size erlang)
A binary of size N takes N+C bytes of storage where C is a small constant

Random access on lists is bad - random access on binaries is far better.

There are primitives to access the individual elements of lists and binaries.

There are also some fancy bit-level things (the binary syntax) so you
can extract ranges of bits from binaries in a convenient manner.

Cheers

/Joe


On Thu, Dec 20, 2018 at 12:48 AM <zxq9@REDACTED> wrote:
>
> On 2018年12月19日水曜日 18時40分05秒 JST Donald Steven wrote:
> > The manual for the function read_file/1 says: Returns {ok, Binary}, where Binary is a binary data object that contains the contents of Filename, or {error, Reason} if an error occurs.
> >
> > What is the type of this "binary data object" (a list?).  (I'll want to access individual elements.)
>
> It is an Erlang binary.
>
>
> 1> Foo1 = "Something I'll write to disk.".
> "Something I'll write to disk."
> 2> Foo2 = <<"Something else I'll write to disk.">>.
> <<"Something else I'll write to disk.">>
> 3> Foo3 = <<1,2,3,4>>.
> <<1,2,3,4>>
> 4> file:write_file("foo1.txt", Foo1).
> ok
> 5> file:write_file("foo2.txt", Foo2).
> ok
> 6> file:write_file("foo3", Foo3).
> ok
> 7> file:read_file("foo1.txt").
> {ok,<<"Something I'll write to disk.">>}
> 8> file:read_file("foo2.txt").
> {ok,<<"Something else I'll write to disk.">>}
> 9> file:read_file("foo3").
> {ok,<<1,2,3,4>>}
>
>
> If the above seems perplexing then check out the docs on Erlang binaries.
> They are awesome, especially when dealing with binary file formats or network data.
>
> http://erlang.org/doc/reference_manual/expressions.html#bit_syntax
> http://erlang.org/doc/programming_examples/bit_syntax.html
> http://erlang.org/doc/man/binary.html
>
> Also, keep in mind that "object" is a heavily overloaded term in computing.
> The docs mean "returns a self-contained thingy that can be labeled and carries
> a type (binary) native to the runtime".
>
> -Craig
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://erlang.org/mailman/listinfo/erlang-questions



More information about the erlang-questions mailing list