0xAX
0xAX

Reputation: 21817

Binary to list strange output

I have following code:

file:write(FileId, Packet),
file:close(FileId),
{ok, FileId1} = file:open("tmp/" ++ integer_to_list(Summ), [read]),
A = file:read_file("tmp/" ++ integer_to_list(Summ)),
{_, B} = A,
io:format(binary_to_list(B));

In the end of function i see io:format B output. But if i make that:

file:write(FileId, Packet),
file:close(FileId),
{ok, FileId1} = file:open("tmp/" ++ integer_to_list(Summ), [read]),
A = file:read_file("tmp/" ++ integer_to_list(Summ)),
{_, B} = A,
S = binary_to_list(B),
io:format(S);

io:format nothing output. Why?

Thank you.

Upvotes: 1

Views: 668

Answers (3)

rvirding
rvirding

Reputation: 20916

The argument to io:format/1 is a format string which must not include any formatting control sequences which require arguments. If this occurs an error is generated. To output raw printable characters use io:put_chars/1.

Upvotes: 0

Yurii Rashkovskii
Yurii Rashkovskii

Reputation: 1152

It does work perfectly well here:

3> {ok, FileId1} = file:open("tmp/" ++ integer_to_list(Summ), [read]),
3> A = file:read_file("tmp/" ++ integer_to_list(Summ)),
3> {_, B} = A,
3> S = binary_to_list(B),
3> io:format(S).
1213

Upvotes: 1

sarnold
sarnold

Reputation: 104040

You should probably not rely on the single-argument io:format/1 function:

3> B="helo\n".  
"helo\n"
4> io:format(B).
helo
ok
5> C="~p".
"~p"
6> io:format(C).
** exception exit: {badarg,[{io,format,[<0.26.0>,"~p",[]]},
                            {erl_eval,do_apply,5},
                            {shell,exprs,6},
                            {shell,eval_exprs,6},
                            {shell,eval_loop,3}]}
     in function  io:o_request/3

If the argument contains any formatting requests, your io:format call may die. I would recommend using a format string such as ~p~n or ~w~n:

1> C="~p".
"~p"
2> io:format("~p~n", [C]).
"~p"
ok

Upvotes: 4

Related Questions