Anything faster than stat(S)? need to determine File or Dir

Jonathan I. Kamens jik at athena.mit.edu
Fri Nov 10 04:38:49 AEST 1989


In article <2586 at unisoft.UUCP> greywolf at unisoft.UUCP (The Grey Wolf) writes:
>Portable, almost.  Usable by anyone, probably not.
>
>It would require being run as a super-user, and it would be fairly quick --
>whether it's faster than a stat or not, I'm not sure.  What you could
>do is, once you get the entry, try and chdir() to it.  If it works, it's
>a directory, otherwise it's a file.  CAVEAT (obvious): this is not fool-
>proof if you're running a system with symbolic links.

  Bad idea for several reasons.  First of all, after you've used
chdir() several times (or even once) to go down a directory tree, you
have to use chdir("..") to get back up to the top.  In general, I find
that it is a bad idea to change the current working directory of a
process unless you are *sure* that you can get back to where you
started.  You're not sure in this case.

  Now, I know that you said "it would require being run as a
super-user", by which I assume that you meant to imply (among other
things) that the program would have read access to all directories and
therefore be able to get back to where it started no matter what.
This is not necessarily true, now that we're in the age of remote
filesystems (NFS, AFS, etc.).  Root on my workstation does not have
root access to NFS filesystems I have mounted.

>I think, IMHO, you're better off going with stat().

  Yup, I think so too.  That's how I do it in the code I've written.

  One final note: an interesting question is whether it's faster to
(a) stat() a file and use opendir() on it only if it's a directory, or
(b) just do the opendir() on it and keep going if the opendir()
succeeds.  I've found that (a) is much faster because opendir() always
does an open() on the file, even when it's not a directory.
Therefore, when you try to opendir() a non-directory, it's got to do
the open, then realize that it's not a directory using fstat, then
close the file.

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



More information about the Comp.unix.wizards mailing list