Question

this code generate Error on file:write_file(Filename, Data, [append]),

{{badmatch,{error,enoent}},[{t,save,2,[{file,"1.erl"},{line,38}]}]}

case file:read_file_info(Filename) of
    {error, Reason} ->
      {ok, IoDevice}=file:open(Filename, [write, binary]),
      file:write_file(Filename, Data, [append]),  % line 38
      file:close(Filename),
      ok;
    {ok, FileInfo} -> ok
  end.

that's wrong?

Was it helpful?

Solution

First, if you want to use write_file() you don't need to open it first. But you will overwrite the whole file each time - you can't append. You should use file:write(IoDevice, Data) instead, and use 'append' instead of 'write' in the options to file:open().

Second, when you close the file, you should give it the IoDevice as parameter, not the Filename.

OTHER TIPS

It seems that there is a race condition in this code.

If I am correct you use the file:open to create a file when it does not exist, and then append some data in it.

It seems that you get the IoDevice before the file is ready to be written in the underlying system, and as you use a different access type (ignoring the file handle you've just created) the append fails.

If you execute the 2 lines in the shell, in 2 separate commands, you will see that it works.

A better code should be:

append(Filename,Data) ->
case file:read_file_info(Filename) of
    {error, enoent} ->
      file:write_file(Filename, Data);  % create the file and write
    {ok, _FileInfo} ->
      file:write_file(Filename, Data,[append]) % append data to existing file
end.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top