[erlang-questions] read_file -- binary data object

zxq9@REDACTED zxq9@REDACTED
Thu Dec 20 00:48:27 CET 2018


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



More information about the erlang-questions mailing list