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

File io 如何在erlang中打开具有相关路径的文件?,file-io,erlang,erlang-shell,File Io,Erlang,Erlang Shell,我一直在摆弄erlang,我试图找到如何使用函数读取.txt文件,但我就是不知道如何从相关路径读取它。基本上,这就是我构建项目目录的方式: project/ | ebin/ | priv/ | include/ | src/ 我所有的.beam文件都在ebin目录中,我需要打开“priv/”目录中的.txt文件 这是我的代码: from_file(FileName) -> {ok, Bin} = file:read_file(FileName),

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

project/
  |   ebin/
  |   priv/
  |   include/
  |   src/
我所有的.beam文件都在ebin目录中,我需要打开“priv/”目录中的.txt文件

这是我的代码:

from_file(FileName) ->
    {ok, Bin} = file:read_file(FileName),
     ...
调用此函数时,我会传递一个字符串,如:“/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)
如果我将.txt文件与调用函数的.beam文件放在同一个文件夹中,那么如果我只是以文件名“foo.txt”的形式输入,它就可以正常工作

如何使函数从项目的相关路径读取

如果我不能这样做,那么如何读取与.beam文件位于同一目录下的文件夹中的文件

e、 g


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])).

所以我没有用我的应用程序,而是把我的项目的名字放进去了?或者我需要把我的项目文件夹的完整路径放进去吗?仅仅是项目的名称,作为一个atom(所以没有引号,除非它们是单引号),我仍然无法让它工作。。。我应该从哪里调用erlang shell?为了能够调用我的函数,我必须进入目录ebin,然后写入终端
erl
,如果我只是在项目的根文件夹中写入
erl ebin
,那么我无法运行函数:/n您需要从应用程序目录中以
erl-pa ebin
的形式运行它。
-pa
告诉VM加载beam文件并在该目录中找到它。
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])).