How to write a current directory finder?

Roland McGrath mcgrath at paris.Berkeley.EDU
Sun Apr 2 15:08:07 AEST 1989


I've written a `getcwd' function (finds the absolute pathname of the current
working directory), and it works; but it's immensely slow!

The method I've used is this:

Starting with `.', get the device and i-node numbers of each directory, back
up to `..', search the directory, checking each file for matching numbers,
and when one is found, add its name to the beginning of the path.
Then, get the device and i-node numbers of that directory, back up to its
parent, and search for matching numbers, repeating until a directory and its
parent have the same device and i-node numbers (because /.. is /).

Since my function is about 10 times slower than /bin/pwd, this is obviously
not the optimum method.

Since the manpage for `getwd' on my system (Sun Unix 3.2) warns that a
failing `getwd' call may leave the current directory in the wrong place, I
assume that `getwd' moves around in the process of figuring it out.
But I don't see how this helps, using the same basic logic as my method.
You trade time constructing a big `../../../../..' name and using that in
all the lookups for moving around and cutting out all the `..'s.
But can that really make such a difference?
--
	Roland McGrath
	Free Software Foundation, Inc.
roland at wheaties.ai.mit.edu, mit-eddie!wheaties.ai.mit.edu!roland
Copyright 1989 Roland McGrath, under the GNU General Public License, version 1.



More information about the Comp.unix.wizards mailing list