How to read a erlang file in elixir?

Hi guys,

In the following code I created a “erlang file” with 10 lists. I tried to read the lists back and but I got only the last list.

import :erlang, only: [binary_to_term: 1, term_to_binary: 1]
path = "/home/x/y"

# I write ,for example, 10 lists into a file.

for a_map <- results do 
 # 10 lists made
 bin = :erlang.term_to_binary(a_list)

# Now I want to read the lists back.
# The following code shows only the last list:

for a_map <- results do!(path) |> :erlang.binary_to_term 

What is the right code?

aren’t you writing to the same file? so the last one is what is persisted in the file…

Hi, That is weird. I expected 10 “list records” in the file and not the last one.

From the documentation of File.write/3:

The file is created if it does not exist. If it exists, the previous contents are overwritten.

So, each call to File.write/3 overwrites what you have written before.

I think the easiest way is to create a single list, containing all items, converting that list to a binary and write the combined binary into a file.

Hi Nobbz,

Thanks for your answer.

I shall try it but I am a little bit afraid because I have 3000 “list records” .
It should be something like: my_single_list = [ [list1], [list2],…[list3000] ] ?

bin = :erlang.term_to_binary(my_single_list)

I give it a try.

Hi outlog,

Thanks for your suggestion. I am learning to use the erlang stuf in my elixir program, so I am not familiar with it. Nobbz gave me a suggestion which I shall try.

1 Like

Of course you cal also use, IO.binwrite and IO.binread to write and read a stream of binary terms, but that might be harder to read in, as you need to do the chunking manually.

Hi Nobbz,
I am goiing to do my homework. Thanks.

Might just be easier to use DETS?

1 Like