Dot files always first in directory?

Heather Burris heather at maui.cs.ucla.edu
Sat May 6 02:08:39 AEST 1989


In article <535 at biar.UUCP> trebor at biar.UUCP (Robert J Woodhead) writes:
>In article <11108 at bloom-beacon.MIT.EDU> jik at athena.mit.edu (Jonathan I. Kamens) writes:
>>It it safe to assume when writing a program which manipulates
>>directories that . and .. will always be the first two entries in a
>>directory?
>
>No.  It isn't safe to make this assumption.  Even if it is true on your
>machine, it may not be on another implementation (it isn't on my Xenix
>box, according to a quick test using ``l''), and it surely will be changed
>_just_to_smite_your_program_ at some time in the future.

This and other answers about why it isn't safe to assume that . and .. are
first in the directory are correct, but they are correct for the wrong
reasons.  There are two reasons that I can think of for why it is not safe 
to assume that . and .. are first:

	1) The basic reason, true on all UNIX systems that I know of,
	is that . and .. are links and because of file system damage they
	could be removed.  Therefore it is not safe to skip the first
	two directory entries blindly.

	2) The second reason is portability.  On current BSD systems, mkdir
	is a system call and is an atomic operation and therefore assuming
	that . and .. are always present and always first is pretty safe.  
	However, on older UNIX systems, a mkdir is done by using mknod() 
	and then linking in . and .. to the new directory; 3 seperate
	system calls. If the mkdir command were to be interrupted by a 
	system crash, . and .. would not get linked in.  Not all fsck's 
	check for . and .. so a directory can be missing these permanently.  
	Also, to patch up a damaged filesystem, the super user can manually
	link in . and/or .. and then these entries would get whereever
	there is an open spot in the directory and not necessarily at the
	beginning.

The reasons given about using ls to check what could come before . and
.. (and giving examples of characters that would come before . in the
ASCII sorting sequence) are bogus, because ls sorts the directory before
printing it.  If you want to see the "real" order of directory entries, 
i.e. the order that readdir() will present, use the command:

	od -c <directory name>


Heather Burris, UCLA



More information about the Comp.unix.wizards mailing list