erlang

What are common causes for getting {error, enoent} for file:get_cwd()?


I am using file:get_cwd()/0 and I am seeing errors from it, i.e. {error, enoent}. What could be the underlying issue causing this error?


Solution

  • If you look at the UNIX manual page for getcwd(3), which is used to implement file:get_cwd/0 on such systems, you'll find the following explanation of the ENOENT error result:

    ENOENT The current working directory has been unlinked.

    In other words, this error occurs if the current working directory has been deleted out from under the Erlang process. A number of similar explanations of enoent exist in the documentation for the file module.

    Try the following sequence of calls from the erl shell, assuming the directory /tmp/foo does not already exist on your system:

    1> file:make_dir("/tmp/foo").
    ok
    2> cd("/tmp/foo").
    /tmp/foo
    ok
    3> file:get_cwd().
    {ok,"/tmp/foo"}
    4> file:del_dir("/tmp/foo").
    ok
    5> file:get_cwd().
    {error,enoent}
    

    This sequence first creates the new directory /tmp/foo and changes the working directory of the erl process to it. The first call to file:get_cwd() verifies that, as expected, /tmp/foo is the working directory. Then the directory is removed via the call to file:del_dir/1. Because the working directory now no longer exists, the second call to file:get_cwd() returns {error,enoent}.