erlang , How to delete the whole directory which is not empty?


How to delete the whole directory which is not empty?

Question:

Tag: erlang

I want to clean the temporary for collecting resource. The file module only has del_dir/1 which require the directory is empty. But there is not function the get the all files in the directory (with absolute path")

The source code is as follows, how to correct it?

 delete_path(X)->
    {ok,List} = file:list_dir_all(X), %% <--- return value has no absolute path here
    lager:debug("_229:~n\t~p",[List]),
    lists:map(fun(X)->
                      lager:debug("_231:~n\t~p",[X]),
                        ok = file:delete(X)
                end,List),
    ok = file:del_dir(X),
    ok.

Answer:

You can delete a directory via console command using os:cmd, though it's a rough approach. For unix-like OS it will be:

os:cmd("rm -Rf " ++ DirPath).

If you want to delete a non-empty directory using appropriate erlang functions you have to do it recursively. The following example from here shows how to do it:

-module(directory).
-export([del_dir/1]).

del_dir(Dir) ->
   lists:foreach(fun(D) ->
                    ok = file:del_dir(D)
                 end, del_all_files([Dir], [])).

del_all_files([], EmptyDirs) ->
   EmptyDirs;
del_all_files([Dir | T], EmptyDirs) ->
   {ok, FilesInDir} = file:list_dir(Dir),
   {Files, Dirs} = lists:foldl(fun(F, {Fs, Ds}) ->
                                  Path = Dir ++ "/" ++ F,
                                  case filelib:is_dir(Path) of
                                     true ->
                                          {Fs, [Path | Ds]};
                                     false ->
                                          {[Path | Fs], Ds}
                                  end
                               end, {[],[]}, FilesInDir),
   lists:foreach(fun(F) ->
                         ok = file:delete(F)
                 end, Files),
   del_all_files(T ++ Dirs, [Dir | EmptyDirs]).

Related:


How to invoke Erlang function with variable?


erlang
4> abs(1). 1 5> X = abs. abs 6> X(1). ** exception error: bad function abs 7> erlang:X(1). 1 8> Is there any particular reason why I have to use the module name when I invoke a function with a variable? This isn't going to work for me because, well,...

How to delete the whole directory which is not empty?


erlang
I want to clean the temporary for collecting resource. The file module only has del_dir/1 which require the directory is empty. But there is not function the get the all files in the directory (with absolute path") The source code is as follows, how to correct it? delete_path(X)-> {ok,List} =...

Passing map type argument in function in Erlang complains error


erlang,erlang-shell
Here's my code snippet. %% test.erl -export([count_characters/1]). count_characters(Str) -> count_characters(Str, #{}). count_characters([H|T], #{H := N} = X) -> count_characters(T, X#{H := N+1}); count_characters([H|T], X) -> count_characters(T, X#{H => 1}); count_characters([], X) -> X. %% ErShell 1> c(test). test.erl:19: illegal use of variable 'H' in map test.erl:20: illegal use of variable...

Jabber user going offline: Why the two different scenarios?


android,erlang,xmpp,ejabberd,user-presence
I have an Android client working in tandem with ejabberd XMPP server. Observations: Scenario 1: When I swipe-right the app (kill the app), the user goes offline on the server immediately. Its status is changed to offline at that very instant. Scenario 2: However, when I simply shut-down the Wi-fi...

What is the difference between .app and .app.src files in Erlang?


erlang
I found these description in the Erlang doc and learnyousomeerlang.com, but not sure which one is the "Application Resource File". When should I use .app and .app.src? 7.3 Application Resource File http://www.erlang.org/doc/design_principles/applications.html The Application Resource File http://learnyousomeerlang.com/building-otp-applications...

Elixir exrm release crashes on eredis start_link


erlang,elixir,exrm
I'm fairly new to Elixir and this is the first app that I'm attempting to release using exrm. My app interacts with a Redis database for consuming jobs from a queue (using exq), and also stores results of processed jobs in Redis using eredis. My app works perfectly when I...

First word of binary string erlang


functional-programming,erlang,pattern-matching
I need to do something like this <<"Some text in binary">>, and it should return <<"Some">. How can i do it without split function, only by pattern matching and select/if cases with Erlang. Thank you.

Mnesia pagination with fragmented table


pagination,erlang,mnesia
I have a mnesia table configured as follow: -record(space, {id, t, s, a, l}). mnesia:create_table(space, [ {disc_only_copies, nodes()}, {frag_properties, [ {n_fragments, 400}, {n_disc_copies, 1}]}, {attributes, record_info(fields, space)}]), I have at least 4 million records for test purposes on this table. I have implemented something like this Pagination search in Erlang...

Adding to an existing value in Erlang


erlang,record,erl
I am attempting to create a function that stores a number into a record and then adds value X to that number every time the function runs. Value: 5 Run Function (Add One): 1 Value should be: 6 Run Function (Add One): 1 value should be 7 I tried to...

erlang processes and message passing architecture


concurrency,process,erlang,messages
The task I have in hand is to read the lines of large file, process them, and return ordered results. My algorithm is: start with master process that will evaluate the workload (written in the first line of the file) spawn worker processes: each worker will read part of the...

Fetching and updating data in mnesia


erlang,mnesia
I have multiple mnesia tuples like (GroupID is the primary key) {GroupID, GroupName, GroupType, GroupDescription, GroupTag, CreatorID, AdminID, MemberList, Counter}. MemberList = "[email protected],[email protected],[email protected]". GroupName = "Any String Value". % e.g.: "basketball" GroupTag = "comma separated values". % e.g.: "Sports,Cricket,Fifa,Ronaldo" I will pass a character or word to a function. This...

Type errors in dialyzer in function with specified type


erlang,dialyzer
I am receiving an error in dialyzer when it analyzes the following function. -spec do_request(Method, Type, Url, Expect, Headers, Body, Client) -> Response::client_response() when Method :: method(), Type :: content_type(), Url :: url(), Expect :: status_codes(), Headers :: headers(), Body :: body(), Client :: #client{}. do_request(Method, Type, Url, Expect, Headers,...

Erlang syntax error unclear


function,variables,if-statement,functional-programming,erlang
I just got started with Erlang. I am trying if statement. I found out one particular behavior which I do not understand. the following statement does work perfectly. some_comp(Arg1) -> if (cal(Arg1)>50000)->'reached'; true -> 'invalid' end. cal(Arg2)-> %% some calculation. However the following shows an error syntax near if: some_comp(Arg1)...

Convert bitstring to tuple


binary,erlang
I'm trying to find out how to convert an Erlang bitstring to a tuple, but so far without any luck. What I want is to get from for example <<"{1,2}">> the tuple {1,2}....

Where does Elixir/erlang fit into the microservices approach? [closed]


architecture,erlang,docker,elixir,microservices
Lately I've been doing some experiments with docker compose in order to deploy multiple collaborating microservices. I can see the many benefits that microservices provide, and now that there is a good toolset for managing them, I think that it's not extremely hard to jump into the microservices wagon. But,...

ctrl+G in erl doesn't work


unicode,encoding,utf-8,erlang,docker
I'm trying to interconnect erlang nodes, but entering ctrl+G doesn not work: Eshell V6.4.1 (abort with ^G) 1> ^G Eshell V6.4.1 (abort with ^G) 1> ^G Eshell V6.4.1 (abort with ^G) 1> ^G Eshell V6.4.1 (abort with ^G) any idea why this can happen? I was thinking about locale settings,...

Modifying an Erlang Record [duplicate]


erlang,record,erl
This question already has an answer here: Adding to an existing value in Erlang 2 answers I know that a record in Erlang cannot be changed once it has been set. I am attempting to use a record to increase a value. add_new_num() -> Number = random:uniform(6), STR =...

Does the pattern [_|_] in Erlang mean anything specific?


erlang
I am learning Erlang from Learn You Some Erlang and I've seen the pattern [_|_] twice already but couldn't find any info on it. This usage seems superfluous because omitting it from (1) and subsituting it with _ in (2) yields the same result without degrading readability. It is my...

gen_server handle_info/2 clarification


syntax,erlang,gen-server
While reading through Erlang and OTP in action, I ran across some weird syntax regarding records that I'm having trouble wrapping my head around. I'm hoping someone can clarify what's going on in the handle_info for timeouts here: handle_info({tcp, Socket, RawData}, State) -> do_rpc(Socket, RawData), RequestCount = State#state.request_count, {noreply, State#state{request_count...

Find the minimum value in a map


erlang
I have a map organized as follows.Key is a simple term lets say an integer but the value is complex tuple {BB,CC,DD}. What is the best way to find the minimum CC in the map ? So far I have the following -module(test). -author("andre"). %% API -export([init/0]). init() -> TheMap...

How to list all the bucket types in riak?


erlang,riak
Using Riak Client(erlang), I can list all the buckets of the default bucket type. But how can I list all the bucket types? Or If I can't do this by the client, how can I find out about this?

How to rewrite Erlang combinations algorithm in Elixir?


functional-programming,erlang,elixir
I've been tinkering with Elixir for the last few weeks. I just came across this succinct combinations algorithm in Erlang, which I tried rewriting in Elixir but got stuck. Erlang version: comb(0,_) -> [[]]; comb(_,[]) -> []; comb(N,[H|T]) -> [[H|L] || L <- comb(N-1,T)]++comb(N,T). Elixir version I came up with...

Riak mapReduce fails with > 15 records


mapreduce,erlang,riak
Problem I've been learning Riak and ran into an issue with mapReduce. My mapReduce functions work fine when there's 15 records, but after that, it throws a stack trace error. I'm new to Riak and Erlang, so I'm unsure whether it's my code or it's Riak. Any advice on how...

Erlang spawning large amounts of C processes


c,multithreading,lua,erlang,ffi
I've been looking into how I could embed languages (let's use Lua as an example) in Erlang. This of course isn't a new idea and there are many libraries out there that can do this. However I was wondering if it was possible to start a Genserver with state which...

Erlang: Returning a function from a function


erlang
I know Erlang supports anonymous functions. My question is, can I return a function from a function then call that returned function from outside? If so, how do I do it? I know this is possible in many languages such as C and Python. Here is what I tried to...

erlang message passing architecture


process,erlang,messaging
In erlang if two processes A and B are sending message to a process C simultaneously. Will there be a race condition? C ! {very large message} sent by A C ! {very large message} sent by B Will C receive the complete message from A and then proceed for...

How to read and write id3v1 and id3v2 tags in Elixir


erlang,mp4,elixir,id3
I would like to scan music files and read/write metadata using Elixir (this whole project is about learning Elixir - so please don't tell me to use Python!). As I understand it, I have two choices: call a system utility or (as no libraries exist in Erlang or Elixir that...

How to upgrade from R16B to 17? list_to_binary breaks if there are Chinese characters inside


erlang
We are using R16B03-1 and trying to upgrade to R17. iolist_to_binary and list_to_binary breaks if there are Chinese characters inside. I googled and found following links to explain the problem. http://www.erlang.org/news/71 The default encoding of Erlang files has been changed from ISO-8859-1 to UTF-8. The encoding of XML files has...

Getting a sibling process in Elixir


erlang,elixir,otp
I have an Elixir/Erlang process tree: parent (Supervisor) ├── child1 (GenServer) └── child2 (GenServer) child1 (a DB client) has information that child2 needs to use. What's a good way to pass a reference from the Supervisor process to child2 so that child2 will always have a valid reference to child1?...

Erlang result in accumulator


erlang
I'm trying to write a program that collects all Pythagorean triples equal to a given number; for example, calling main(12) should return [{3,4,5}]. But when I run my code, the answer is []. Can you tell me what I am doing wrong? -module(triples). -export([main/1]). t1(A, B, C) -> {A-2*B+2*C, 2*A-B+2*C,...

Erlang basic syntax error


syntax,erlang
I try to learn Erlang. I've installed a runtime but cannot get it working. The following code: X=3. works, but the following doesn't f(X)->X. or F() ->0. or F([])->[]. etc. all produce "1: syntax error before: '->'" I tried the "word_count" from this tutorial: http://www.ybrikman.com/writing/2012/11/04/seven-languages-in-seven-weeks-erlang/ and I get the same...

Multiple specifications for same function in Erlang header file


erlang
I'm trying to specify a function in a header file. Like so: -spec update(pid(), tuple(tuple(), integer(), atom()), tuple(atom(), atom())) -> tuple(tuple(), integer(), atom()). Now I want to add some extra specification for this function because it has multiple different parameters. update(_Pid, {Specs, infinity, _State}, {Step}) -> timer:sleep(10000), {{Specs, infinity}, {Step}};...

Is ++ operator more expensive than | operator in Erlang?


erlang
I was reading Learn You Some Erlang and I came upon this example in the Recursion chapter. tail_sublist(_, 0, SubList) -> SubList; tail_sublist([], _, SubList) -> SubList; tail_sublist([H|T], N, SubList) when N > 0 -> tail_sublist(T, N-1, [H|SubList]). As the author goes on to explain that there is a fatal...

Fast mutable objects in Erlang


erlang
What is the best approach to store and manage high-performance mutable objects in Erlang? Assume that I want to write really simple online game server with realtime gameplay. Somehow I need to represent player's state in Erlang memory. For example, it could be just a simple tuple like {name, "Bob",...

Pid as erlang maps key?


erlang
Can Pid be maps key ? Build maps from #{} syntax, The error says Pid can not be key. Bug build with maps module, Pid can be key. 18> 18> Pid = self(). <0.39.0> 19> #{Pid => 1}. * 1: illegal use of variable 'Pid' in map 20> 20> M1...

Wait for Node.connect before using :global.whereis_name


erlang,elixir
I have the following function: def join(id) do if Node.connect(:"#{id}@127.0.0.1") do send :global.whereis_name(id), {:join, id} end end I receive the error: (ArgumentError) argument error :erlang.send(:undefined, ... which I assume is because Node.connect does some gathering of information and when I call :global.whereis_name it has not finished yet. If I throw...

Pattern matching the fields of a map in erlang


erlang,erlang-shell
I'm currently reading book << Programming Erlang, 2nd edition >>. When I looked through the pattern matching of Map's field, the code snippet in the book complains some error on my Erlang prompt. %% Book's version 1> Henry8 = #{ class => king, born => 1491, died => 1547 }....

Erlang pass-by-reference nuances


erlang,pass-by-reference
9> A = lists:seq(1,10). [1,2,3,4,5,6,7,8,9,10] 13> Fn = fun (L) -> [0|L] end. #Fun<erl_eval.6.90072148> 14> Fn(A). [0,1,2,3,4,5,6,7,8,9,10] 15> A. [1,2,3,4,5,6,7,8,9,10] If erlang internally passes by reference (see this), why does the value of A not reflect the change? What fundamental am I missing about passing-by-reference or erlang?...

Exception handling in Erlang to Continue execution


exception,error-handling,exception-handling,erlang,ejabberd
What I am trying to do is mochijson2:decode(Ccode) generates any exception or error, program execution should not stop and case branch {error, Reason} should get executed. But when I am trying to get it implemented, it generates error at first line while checking and code doesn't continue execution for lines...

Value from binding in LFE interpreter using Erlang


erlang,lisp,lfe
I'd like to use Lisp Flavored Erlang as a scripting extension language for an Erlang application. If you want, in a similar way GNU Emacs is configured and extended via Emacs Lisp. I know that the argument is wide and structured; but in the specific case of this question I'd...

how to handle low_entropy exception of crypto:strong_rand_bytes(N)?


openssl,erlang
I want to generate cryptographically strong pseudorandom numbers in erlang for session IDs. There is crypto:strong_rand_bytes(N). What if it throws the low_entropy exception? From http://www.erlang.org/doc/man/crypto.html#strong_rand_bytes-1 strong_rand_bytes(N) -> binary() Types: N = integer() Generates N bytes randomly uniform 0..255, and returns the result in a binary. Uses a cryptographically secure prng...

Erlang based chat (load balancing and notifications distribution)


erlang
We are going to develop a backend for our messenger, so I have one idea which I want describe here, maybe someone can give me an advice. 1) Idea: Nginx - redirects request to random node (round robin) -> Erlang cluster - redirects to actual node (we choose node with...

Manipulating XML element to get value from Sub-element in Erlang


xml,erlang,ejabberd
I have this in Packet: {xmlelement,"message", [{"from", "[email protected]/26526129921433241378891365"}, {"to", "[email protected]/30014432481433242528199830"}], [{xmlelement,"received", [{"xmlns", "urn:xmpp:receipts"}, {"id", "018A12FB-0718-4304-87FD-430C59EDB4F9"}], []}]} I just need to get the value of the id attribute under the received XML element....

Getting SSL related error against my request to Ejabberd


android,sockets,ssl,erlang,ejabberd
Following is the code snippet where i open a socket to write APNS notifications on: get_socket()-> %%Options Options = [{certfile, ?Cert}, {keyfile, ?Key}, {mode, binary}], %%ssl connection ssl:connect(?Address, ?Port, Options, infinity) . close_socket(Socket)-> ssl:close(Socket). I am getting the following crash in my ejabberd.log file 2015-06-05 12:33:17.112 [error] <0.3134.0> gen_fsm <0.3134.0>...

Erlang driver erl_errno issue


erlang,erlang-driver
I am playing with erl_driver. Start callback of my driver is below: ErlDrvData drv_start(ErlDrvPort port, char* command) { char* file_name = command + sizeof(drv_name); GenTtyData* port_data = (GenTtyData*)driver_alloc(sizeof(GenTtyData)); erl_errno = gt_open(file_name, &port_data->file); if (erl_errno != 0) { // Assertion there is just to show you my intention assert(erl_errno == ENOENT);...

How to make a gen_server reply with a message?


erlang
I have the gen_server shown below. It works for the most part. However when I start it from the shell the replies come right back to the shell prompt. I would have expected them to be sent as messages back to the shells pid and then I would use flush()...

erlang os:cmd() command with UTF8 binary


unicode,encoding,erlang,utf
I'm trying to get an Erlang function to execute a bash command containing unicode characters. For example, I want to execute the equivalent of: touch /home/jani/ჟანიweł I put that command in variable D, for example: io:fwrite("~ts", [list_to_binary(D)]). touch /home/jani/ჟანიwełok but after I execute: os:cmd(D) I get file called á??á??á??á??weÅ?. How...

Does Erlang has Map?


erlang
It seems that Erlang introduced maps in version R17A. But, if I go to downloads I only see version 17.5, there's no version R17A. So, is it released and stable yet? Does the latest stable Erlang has Map support?...

Why doesn't spawn link cause the calling process to die?


erlang,erlang-shell
From the example given here, Erlang and process_flag(trap_exit, true) -module(play). -compile(export_all). start() -> process_flag(trap_exit, true), spawn_link(?MODULE, inverse, [***0***]), loop(). loop() -> receive Msg -> io:format("~p~n", [Msg]) end, loop(). inverse(N) -> 1/N. If I run it as, A = spawn(play, start, []). The spawned process <0.40.0> dies as it is suppose...

passing arrays to a function in erlang


arrays,function,erlang,arguments
I am new to erlang programming and as a matter of fact no very experienced programmer. I need to pass an array to a function and then manipulate it.. however I have so far not be this what I found. module(easy). export([myfunction/1]). myfunction([myarray]) -> %% mycode.. hier I will need...