2014-10-10 62 views
1

我一直在搞erlang,我試圖找到如何用函數讀取.txt文件,但我無法弄清楚如何從相關路徑讀取它。基本上這是我如何構建我的項目目錄:如何用erlang中的相關路徑打開文件?

project/ 
    | ebin/ 
    | priv/ 
    | include/ 
    | src/ 

我所有的.beam文件是在EBIN目錄,我需要打開一個txt文件是在「私法/」目錄。

這是我的代碼:

from_file(FileName) -> 
    {ok, Bin} = file:read_file(FileName), 
    ... 

當我調用這個函數,我通過類似的字符串:「/絕對/路徑/到/項目/目錄/私法」,但每一次我得到這個錯誤。

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) 

如果我在從我調用函數的.beam文件同一文件夾中的.txt文件,然後它工作正常,如果我只輸入一個文件名「foo.txt的」。

如何從項目的相關路徑中讀取函數?

如果我不能這樣做,那麼我該如何讀取位於同一目錄下的.beam文件中的文件夾內的文件?

例如

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

回答

4

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

所以不是my_application之類的我只是把我的項目的名稱?或者我需要把我的項目文件夾的完整路徑? – sokras 2014-10-10 17:00:37

+0

只是項目的名稱,作爲一個原子(所以沒有引號,除非它們是單引號) – 2014-10-10 17:14:24

+0

我仍然要讓它工作......我應該從哪裏調用erlang shell?爲了能夠調用我的函數,我必須進入目錄ebin,然後在終端erl中寫入,如果我只在項目的根文件夾中寫入erl ebin,那麼我無法運行函數:/ – sokras 2014-10-11 07:29:53

相關問題