e r l a n g : c o o k b o o k

/ Erlang.FileIsADirectory

This Web


WebHome 
WebChanges 
TOC
NewRecipe 
WebTopicList 
WebStatistics 

All Webs


Chicken
Cookbook
Erlang
Know
Main
Plugins
Sandbox
Scm
TWiki  

Erlang Links


Erlang.org
Erlang Wiki
ErlMan
Erlang Wiki
The Jungerl
Erlang-fr.org
Joe Armstrong
Lambda the Ultimate

Erlang Web Ring


[Prev]: Joe Armstrong's Page
[Next]: Joe Armstrong's Page

Testing Whether A File Is A Directory

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.


Comments about this recipe

Contributors

Based on work by NoelWelsh.

-- BrentAFulgham - 31 Aug 2004

CookbookForm
TopicType: Recipe
ParentTopic: FileRecipes
TopicOrder: 010

 
 
Copyright © 2004 by the contributing authors. All material on the Erlang Cookbook web site is the property of the contributing authors.
This material can be redistributed and/or modified under the terms of the GNU Lesser General Public License (LGPL), version 2.1, as published by the Free Software Foundation.
Ideas, requests, problems regarding Schematics Cookbook? Send feedback.
/ You are Main.guest