3

我一直在搞乱 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 文件位于同一目录中的文件夹内的文件?

例如

project/
  |   ebin/
  |    |  folder_with_the_doc_that_I_want_to_read/
  |   priv/
  |   include/
  |   src/
4

1 回答 1

7

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])).
于 2014-10-10T16:45:23.393 回答