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