xref: /csrg-svn/lib/libc/gen/getcwd.c (revision 10127)
1*10127Ssam /*	@(#)getcwd.c	4.4	(Berkeley)	01/04/83	*/
29986Ssam 
39986Ssam /*
49986Ssam  * Getwd
59986Ssam  */
610088Ssam #include <sys/param.h>
710088Ssam #include <sys/stat.h>
810088Ssam #include <sys/dir.h>
99986Ssam 
109986Ssam #define	dot	"."
119986Ssam #define	dotdot	".."
129986Ssam 
13*10127Ssam #define	prexit(s)	{ strcpy(np, s); return (NULL); }
14*10127Ssam 
1510088Ssam static	char *name;
169986Ssam 
1710088Ssam static	DIR *file;
1810088Ssam static	int off;
1910088Ssam static	struct stat d, dd;
2010088Ssam static	struct direct *dir;
219986Ssam 
229986Ssam char *
239986Ssam getwd(np)
2410088Ssam 	char *np;
259986Ssam {
2610088Ssam 	dev_t rdev;
2710088Ssam 	ino_t rino;
289986Ssam 
2910088Ssam 	off = -1;
309986Ssam 	*np++ = '/';
319986Ssam 	name = np;
329986Ssam 	stat("/", &d);
339986Ssam 	rdev = d.st_dev;
349986Ssam 	rino = d.st_ino;
359986Ssam 	for (;;) {
369986Ssam 		stat(dot, &d);
379986Ssam 		if (d.st_ino==rino && d.st_dev==rdev)
389986Ssam 			goto done;
399986Ssam 		if ((file = opendir(dotdot)) == NULL)
40*10127Ssam 			prexit("getwd: cannot open ..");
419986Ssam 		fstat(file->dd_fd, &dd);
4210126Ssam 		if (chdir(dotdot) < 0)
43*10127Ssam 			prexit("getwd: cannot chdir to ..");
4410126Ssam 		if (d.st_dev == dd.st_dev) {
459986Ssam 			if(d.st_ino == dd.st_ino)
469986Ssam 				goto done;
479986Ssam 			do
489986Ssam 				if ((dir = readdir(file)) == NULL)
49*10127Ssam 					prexit("getwd: read error in ..");
509986Ssam 			while (dir->d_ino != d.st_ino);
5110126Ssam 		} else
5210126Ssam 			do {
539986Ssam 				if ((dir = readdir(file)) == NULL)
54*10127Ssam 					prexit("getwd: read error in ..");
559986Ssam 				stat(dir->d_name, &dd);
569986Ssam 			} while(dd.st_ino != d.st_ino || dd.st_dev != d.st_dev);
579986Ssam 		closedir(file);
589986Ssam 		cat();
599986Ssam 	}
609986Ssam done:
619986Ssam 	name--;
629986Ssam 	if (chdir(name) < 0)
63*10127Ssam 		prexit("getwd: can't change back");
649986Ssam 	return (name);
659986Ssam }
669986Ssam 
679986Ssam cat()
689986Ssam {
699986Ssam 	register i, j;
709986Ssam 
719986Ssam 	i = -1;
729986Ssam 	while (dir->d_name[++i] != 0);
739986Ssam 	if ((off+i+2) > 1024-1)
749986Ssam 		return;
759986Ssam 	for(j=off+1; j>=0; --j)
769986Ssam 		name[j+i+1] = name[j];
779986Ssam 	if (off >= 0)
789986Ssam 		name[i] = '/';
799986Ssam 	off=i+off+1;
809986Ssam 	name[off] = 0;
819986Ssam 	for(--i; i>=0; --i)
829986Ssam 		name[i] = dir->d_name[i];
839986Ssam }
84