finding out if a directory is empty in C program

Jonathan I. Kamens jik at athena.mit.edu
Tue May 7 18:44:38 AEST 1991


In article <1991May3.155817.1807 at visionware.co.uk>, chris at visionware.co.uk (Chris Davies) writes:
|> >In article <1991Apr25.022029.5476 at csc.canberra.edu.au>, rvp at softserver.canberra.edu.au (Rey Paulo) writes:
|> >|> Is there any system call or library routine in UNIX which tests whether
|> >|> a directory is empty?
|> In article <1991Apr25.223540.19303 at athena.mit.edu> jik at athena.mit.edu (Jonathan I. Kamens) writes:
|> >No.  You open the directory with opendir() and read it, and if the only
|> >entries in it are "." and "..", it's empty.  Just like in a shell script
|> >(except the script uses ls, or shell wildcard expansion, instead of opendir()).
|> Why couldn't you use stat() and check whether the number of links == 2 ?
|> Most of the time it's not possible (well, not recommended) for _users_ to
|> hard-link to a directory, so the link-count wouldn't be wrong.

  First of all, only subdirectoris change the link count of a directory.  So
stat()ing the directory and checking its link count will detect only whether
or not it has subdirectories, not whether or not it is empty.

  Second, stat()ing and checking the link count to find out the number of
subdirectories is a hack that is not guaranteed to work on every system and
that is not required to work according to POSIX (at least, I don't think it
is, although I am interested in being corrected).   Operating Systems that
don't really put entries for "." and ".." in a directory (e.g. HP-UX, I
believe) will not have the link counts you're expecting.

  If you want to hard-code the special case operating systems in order to use
the stat() trick to check for subdirectories, you can, but the more reliable
way to do it is opening and reading the directory to see what's in it, and
ignoring "." and ".." if they show up.

-- 
Jonathan Kamens			              USnail:
MIT Project Athena				11 Ashford Terrace
jik at Athena.MIT.EDU				Allston, MA  02134
Office: 617-253-8085			      Home: 617-782-0710



More information about the Comp.unix.questions mailing list