문제

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?

도움이 되었습니까?

해결책

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.

다른 팁

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.
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top