[erlang-questions] read_file -- binary data object
zxq9@REDACTED
zxq9@REDACTED
Thu Dec 20 07:42:01 CET 2018
On 2018年12月19日水曜日 19時04分17秒 JST you wrote:
> Thanks Craig. I don't think I expressed my question well.
>
> Taking your foo1,txt example, when I read it back
> (file:read_file("foo1.txt"), how do I access the individual characters
> of "Something I'll write to disk." That is, if
> file:read_file("foo1.txt") yields {ok,<<"Something I'll write to
> disk.">>}, how do I read the "S", then the "o", etc.?
Gotcha
Once I have a binary I can loop over it the same way I would a list.
Continuing with our previous example of "foo1.txt"...
1> PrintCodepoints = fun
1> P(<<Char, Rest/binary>>) ->
1> ok = io:format("Codepoint: ~w~n", [Char]),
1> P(Rest);
1> P(<<>>) ->
1> io:format("Done!~n")
1> end.
#Fun<erl_eval.30.99386804>
2> {ok, Bin} = file:read_file("foo1.txt").
{ok,<<"Something I'll write to disk.">>}
3> PrintCodepoints(Bin).
Codepoint: 83
Codepoint: 111
Codepoint: 109
Codepoint: 101
Codepoint: 116
Codepoint: 104
Codepoint: 105
Codepoint: 110
Codepoint: 103
Codepoint: 32
Codepoint: 73
Codepoint: 39
Codepoint: 108
Codepoint: 108
Codepoint: 32
Codepoint: 119
Codepoint: 114
Codepoint: 105
Codepoint: 116
Codepoint: 101
Codepoint: 32
Codepoint: 116
Codepoint: 111
Codepoint: 32
Codepoint: 100
Codepoint: 105
Codepoint: 115
Codepoint: 107
Codepoint: 46
Done!
ok
Hm. That came out a bit longer vertically than I intended, but you get the idea.
Obviously you would want to define that as a normal function, not a named lambda, but the shell is really convenient for just showing you how it would go.
codepoints(<<Char, Rest/binary>>) ->
ok = io:format("Codepoint: ~w~n", [Char]),
codepoints(Rest);
codepoints(<<>>) ->
io:format("Done!~n").
Put anything in there you might want to imagine.
-Craig
More information about the erlang-questions
mailing list