How to empty a file

,

Is there a way to empty a file which is not closing and opening with :write?

Delete and touch?!

Ok, I meant something less expensive. I was thinking more to use IO, otherwise I would just close and open it.

Depending on the write mode, you might not need to do anything. If you open the file in :write mode, not combined with read, the file will be truncated upon opening. Otherwise, you could truncate it yourself (tip: check functions in Erlang file if the ones in the Elixir File module are missing what you need)

1 Like

I thought it would be understood by the context: I would like to use IO because the File will be used repeatedly while it’s opened, so I don’t want to open and close it 2-3 times a minute. that’s why I’m searching for a solution less expensive than using file. But thanks, meanwhile I will search in Erlang’s docs.

You can use the Erlang file module function position/2 and truncate/1 to set the position at the beginning of the file and truncate it:

file |> :file.position(:bof) |> :file.truncate()
2 Likes

If you are persisting erlang terms, dets may be a good fit.
It have a delete_all_object.

Also, looking at the code of the dets delete_all_objects function point me here: http://erlang.org/doc/man/file.html#truncate-1