如何在erlang中打开具有相关路径的文件?

sok*_*ras 2 erlang file-io erlang-shell

我一直在搞乱erlang,我试图找到如何使用函数读取.txt文件,但我只是想不通如何从相关路径读取它。基本上,这就是我构造项目目录的方式:

project/
  |   ebin/
  |   priv/
  |   include/
  |   src/
Run Code Online (Sandbox Code Playgroud)

我所有的.beam文件都位于ebin目录中,我需要打开“ priv /”目录中的.txt文件。

这是我的代码:

from_file(FileName) ->
    {ok, Bin} = file:read_file(FileName),
     ...
Run Code Online (Sandbox Code Playgroud)

当我调用此函数时,我传递了一个字符串:“ / absolute / path / to / project / directory / priv”,但是每次都会出现此错误。

exception error: no match of right hand side value {error,enoent}
     in function  read_mxm:from_file/1 (src/read_mxm.erl, line 34)
     in call from mr_tests:wc/0 (src/mr_tests.erl, line 21)
Run Code Online (Sandbox Code Playgroud)

如果我将.txt文件与从其中调用该函数的.beam文件放在同一文件夹中,那么如果我只是输入文件名“ foo.txt”,则该文件就可以正常工作。

如何使功能从项目的相关路径读取?

如果无法通过这种方式进行操作,那么如何读取与.beam文件位于同一目录下的文件夹中的文件?

例如

project/
  |   ebin/
  |    |  folder_with_the_doc_that_I_want_to_read/
  |   priv/
  |   include/
  |   src/
Run Code Online (Sandbox Code Playgroud)

Sou*_*lls 5

Erlang提供了用于确定各种应用程序目录(包括ebin和priv)位置的功能。code:priv_dir像下面这样使用函数(带有故障转移案例):

read_priv_file(Filename) ->
    case code:priv_dir(my_application) of
        {error, bad_name} ->
            % This occurs when not running as a release; e.g., erl -pa ebin
            % Of course, this will not work for all cases, but should account 
            % for most
            PrivDir = "priv";
        PrivDir ->
            % In this case, we are running in a release and the VM knows
            % where the application (and thus the priv directory) resides
            % on the file system
            ok
    end,
    file:read_file(filename:join([PrivDir, Filename])).
Run Code Online (Sandbox Code Playgroud)