Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to open file with relevant path in erlang?

I have been messing around with erlang and I was trying to find how to read .txt file with a function but I just can't figure out how to read it from a relevant path.Basically this is how I have constructed my project directories:

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

All my .beam files are in the ebin directory and I need to open a .txt file that is in the "priv/" directory.

This is my code:

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

When I call this function, I pass a string like: "/absolute/path/to/project/directory/priv" but I get this error every time.

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)

If I have the .txt file in the same folder with the .beam file from which I am calling the function then it works fine if I just input as a filename "foo.txt".

How can I make the function read from a relevant path of the project?

If I can't do it this way, then how can I read a file that is inside a folder in the same directory with the .beam file?

e.g.

project/
  |   ebin/
  |    |  folder_with_the_doc_that_I_want_to_read/
  |   priv/
  |   include/
  |   src/
like image 641
sokras Avatar asked Oct 15 '25 17:10

sokras


1 Answers

Erlang provides functions for determining the location of various application directories, including ebin and priv. Use the function code:priv_dir (with a failover case), like so:

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])).
like image 93
Soup d'Campbells Avatar answered Oct 18 '25 18:10

Soup d'Campbells



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!