erlang, writing integer values to a file
I want to print integer values to a file. I am able to write string values to the file, but when I try to write an integer value it gives an error:
%this works fine
{ok, F}=file:open("bff.txt", [read,write]),
Val="howdy",
file:write(F,Val).
%this gets compiled, but results in error {error, badarg} while executing
{ok, F}=file:open("bff.txt", [read,write]),
Val=23424,
file开发者_高级运维:write(F,Val).
Any suggestions?
Actually I want to write a benchmarking code for a web server and I need to write all the values of times and no of requests to an output file, and then I'll use it to plot graph with gnuplot.Use integer_to_list/1
to convert integers to a list for file:write/2
.
{ok, F}=file:open("bff.txt", [read,write]),
Val=integer_to_list(23424),
file:write(F,Val).
This is because file:write
only can output strings. An alternative is to use functions in the io
module which also work on files. So io:write(File, Val)
will work. You can alternatively use formatted io functions io:format
. It really depends how you wish to format the data and how they are to be read, just writing integers with io:write
will not be very useful if you intend to read them.
You may use term_to_binary and binary_to_term:
{ok, F} = file:open("bff.txt", [read,write]),
Val = [1,2,3,4],
Data = term_to_binary(Val),
file:write(F, Data),
{ok, BinaryData} = file:read_file("bff.txt"),
Val = binary_to_term(BinaryData),
io:format("~s~w~s", ["Value: ", Val, "\n"]).
精彩评论