Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!dali.cs.montana.edu!uakari.primate.wisc.edu!sdd.hp.com!think.com!mintaka!bloom-picayune.mit.edu!athena.mit.edu!jik From: jik@athena.mit.edu (Jonathan I. Kamens) Newsgroups: comp.unix.questions Subject: Re: finding out if a directory is empty in C program Message-ID: <1991May7.084438.16029@athena.mit.edu> Date: 7 May 91 08:44:38 GMT References: <900@homer.UUCP> <1991Apr15.180550.14750@beaver.cs.washington.edu> <1991Apr18.054735.6733@metapro.DIALix.oz.au> <1991Apr25.022029.5476@csc.canberra.edu.au> <1991Apr25.223540.19303@athena.mit.edu> <1991May3.155817.1807@visionware.co.uk> Sender: news@athena.mit.edu (News system) Organization: Massachusetts Institute of Technology Lines: 33 In article <1991May3.155817.1807@visionware.co.uk>, chris@visionware.co.uk (Chris Davies) writes: |> >In article <1991Apr25.022029.5476@csc.canberra.edu.au>, rvp@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@athena.mit.edu> jik@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@Athena.MIT.EDU Allston, MA 02134 Office: 617-253-8085 Home: 617-782-0710