How to store tuple and its size in a file in erlang?

73 Views Asked by At

I have created a gen_server that should receive a tuple sent from the erlang shell and write it to a file along with the tuple size.

Example: the input received is {"A","B","C","D"}, and it should be written to a file as:

{"A","B","C","D"};4

and so on. The gen_server should also receive new inputs and store them in a txt file each on a new line.

I have tried but my code is not generating the required output. Assume I have written basic gen_server code with start_link, init, handle_call, handle_cast, handle_info, terminate and code_change.

1

There are 1 best solutions below

1
7stud On

Try this:

go() ->
    Tuple = {"A", "B", "C", "D"},
    Length = tuple_size(Tuple),
    {ok, TupleFile} = file:open("tuples.txt", [append]),
    file:write(TupleFile, 
               io_lib:format("~p;~w~n", [Tuple, Length])
              ),
    file:close(TupleFile).

io_lib:format() is like io:format() except instead of writing the string to the shell, io_lib:format() returns the string.

In the shell:

1> c(a).
a.erl:2:2: Warning: export_all flag enabled - all functions will be exported
%    2| -compile(export_all).
%     |  ^

{ok,a}

2> a:go().
ok

3> 
BREAK: (a)bort (A)bort with dump (c)ontinue (p)roc info (i)nfo
       (l)oaded (v)ersion (k)ill (D)b-tables (d)istribution
                                                                        

~/erlang_programs% cat tuples.txt
{"A","B","C","D"};4