我一直在摆弄 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/
最佳答案
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])).
关于file-io - 如何在erlang中打开具有相关路径的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26304126/