6

I want to write to a file in the home directory, so I tried the following command:

:call writefile(["foo"], "~/event.log", "a")

But I got an error:

E482: Can't create file ~/event.log

I am pretty sure that I have write permission for my home directory (of course), and there is not a file with the same name at the specified path.

If I change the destination path to the current path, it works.

Does anyone know what the problem is?

  • 5
    Please don't use screenshots for the commands you tried, but post them as text. This makes it easier to test them because the can be copied and pasted. – Jürgen Krämer Sep 23 at 6:03
  • 1
    You might also like github.com/habamax/vim-godot although I didn't put ctags extension there (it is just in my .ctags) – Maxim Kim Sep 23 at 6:40
15

The tilde is only treated specially if it's used in commands like :w ~/event.log. When used in a string that is passed to a function -- even if this function treats the string argument as a file name -- it has no special meaning. You have to take care of the expansion of the tilde to the home directory yourself.

Vim has an expand() function that can be used for this. So one way to correctly write a file in your home directory is to execute the following command:

call writefile(["foo"], expand("~/event.log"), "a")
| improve this answer | |
  • It works! Thanks for your answer and explanations. – naive231 Sep 23 at 12:10
  • @D.BenKnoble You mean the example in the help file? That does not use a tilde. – Jürgen Krämer Sep 23 at 12:37
  • @JürgenKrämer doh... this is why I prefer text 😂 – D. Ben Knoble Sep 23 at 12:41
6

As Jürgen Krämer said, '~' string won't be interpreted by most vim functions.

Thus, when receiving the string from elsewhere, we may indeed need to expand() the tilde. However, when directly working on hardcoded pathnames as in your MWE, we can also use $HOME as in

call writefile(['foo'], $HOME.'/event.log'), 'a')
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.