Erlang Central

File is a Directory

Revision as of 02:32, 4 September 2006 by Bfulgham (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Problem

You have a list of file names, which includes the names of some directories. You want to test if a name refers to a file or directory.

Solution

There are two predicates from the filelib module that are useful here: filename:is_file, which returns true if a file name corresponds to either a file or a directory, and filename:is_dir, which returns true if a file name corresponds to a directory, but not to a file. You can use filename:is_dir with file:list_dir and filelib:fold_files to create a list of file names that correspond only to directories:

1> file:list_dir(".").
{ok,["xpws_tester.erl",
     "xpws_tester.beam"
     "usr",
     "Uninstall.exe",
     "releases",
     "README",
     "PR.template",
     "lib",
     "Install.ini",
     "Install.exe",
     "hello.txt",
     "fun",
     "erts-5.3.6.3",
     "doc",
     "COPYRIGHT",
     "cookbook.erl",
     "cookbook.beam",
     "complex.erl",
     "complex.beam",
     "bin"]}
2> filelib:is_file("CVS").
false
10> filelib:is_file("bin").
true
11> filelib:is_dir("bin").
true
12> lists:filter(fun(A) -> filelib:is_dir(A) end, FL).    
["usr","releases","lib","erts-5.3.6.3","doc","bin"]

Discussion

You'll want to be a bit careful about the predicates and file manipulating functions you might use in these recipes. In many cases they return tuples containing atoms like ok or nomatch that you should watch out for. It's easy to attempt to combine a few functions and end up with matching errors because you did not remember that a tuple is being returned.