Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check in erlang - if a file is - then do not write a new file

Tags:

file

erlang

my code

save(Filename)->

  {ok, IoDevice} = file:open(Filename, [write, binary]),
  file:write_file(Filename, Data, [append]).

How to check if a file is - then do not write a new file.

And if the file does not exist then write a new file

like image 446
user3572870 Avatar asked Dec 08 '25 03:12

user3572870


2 Answers

If you have a file named x.xml let and it exists:

1> filelib:is_regular("x.xml").
true

But x2.xml does not exist:

2> filelib:is_regular("x2.xml").
false

You can also use is_file instead of you want it to return true for directory names as well.

like image 128
Khorkrak Avatar answered Dec 11 '25 10:12

Khorkrak


write

The file is opened for writing. It is created if it does not exist. If the file exists, and if write is not combined with read, the file will be truncated.

append

The file will be opened for writing, and it will be created if it does not exist. Every write operation to a file opened with append will take place at the end of the file.

Please look here:http://www.erlang.org/doc/man/file.html#open-2

You can also use this function:

ensure_dir(Name) -> ok | {error, Reason}

Types: Name = filename_all() | dirname_all() Reason = file:posix()

The ensure_dir/1 function ensures that all parent directories for the given file or directory name Name exist, trying to create them if necessary.

Returns ok if all parent directories already exist or could be created, or {error, Reason} if some parent directory does not exist and could not be created for some reason.

like image 22
BlackMamba Avatar answered Dec 11 '25 11:12

BlackMamba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!