Erlang Central

File is a Directory

From ErlangCentral Wiki


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.


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(".").
2> filelib:is_file("CVS").
10> filelib:is_file("bin").
11> filelib:is_dir("bin").
12> lists:filter(fun(A) -> filelib:is_dir(A) end, FL).    


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.