xref: /original-bsd/usr.bin/f77/libU77/getcwd_.c (revision 6c57d260)
1 /** F77 NOTE: the getcwd() routine should be in libc.a ! **/
2 /*
3  * return name of working (current) directory
4  */
5 #include	<stdio.h>
6 #include	<sys/param.h>
7 #include	<sys/stat.h>
8 #include	<sys/dir.h>
9 
10 static char	dot[]	= ".";
11 static char	dotdot[] = "..";
12 static char	name[128];
13 
14 char *
15 getcwd()
16 {
17 	int	rdev, rino;
18 	int	fd;
19 	struct	stat	d, dd;
20 	struct	direct	dir;
21 	char	*prepend();
22 	char	*namep = &name[(sizeof name)-1];
23 
24 	*namep = '\0';
25 	stat("/", &d);
26 	rdev = d.st_dev;
27 	rino = d.st_ino;
28 	for (;;)
29 	{
30 		stat(dot, &d);
31 		if (d.st_ino == rino && d.st_dev == rdev)
32 		{
33 			chdir(namep);
34 			return(namep);
35 		}
36 		if ((fd = open(dotdot,0)) < 0)
37 		{
38 			chdir(prepend(namep, dot));
39 			return((char *)0);
40 		}
41 		chdir(dotdot);
42 		fstat(fd, &dd);
43 		if(d.st_dev == dd.st_dev)
44 		{
45 			if(d.st_ino == dd.st_ino)
46 			{
47 				close(fd);
48 				chdir(namep);
49 				return(namep);
50 			}
51 			do
52 			{
53 				if (read(fd, (char *)&dir, sizeof(dir)) < sizeof(dir))
54 				{
55 					close(fd);
56 					chdir(prepend(namep, dot));
57 					return((char *)0);
58 				}
59 			} while (dir.d_ino != d.st_ino);
60 		}
61 		else do
62 		{
63 				if(read(fd, (char *)&dir, sizeof(dir)) < sizeof(dir))
64 				{
65 					close(fd);
66 					chdir(prepend(namep, dot));
67 					return((char *)0);
68 				}
69 				stat(dir.d_name, &dd);
70 			} while(dd.st_ino != d.st_ino || dd.st_dev != d.st_dev);
71 		close(fd);
72 		namep = prepend(prepend(namep, dir.d_name), "/");
73 	}
74 }
75 
76 char *
77 prepend(p, n)
78 char *p;
79 char *n;
80 {
81 	int i = 0;
82 
83 	while (i < DIRSIZ && *n)
84 	{
85 		n++; i++;
86 	}
87 	while (i--)
88 		*--p = *--n;
89 	return(p);
90 }
91 
92 /*
93 char id_getcwd[] = "@(#)getcwd_.c	1.2";
94  * Get pathname of current working directory.
95  *
96  * calling sequence:
97  *	character*128 path
98  *	ierr = getcwd(path)
99  * where:
100  *	path will receive the pathname of the current working directory.
101  *	ierr will be 0 if successful, a system error code otherwise.
102  */
103 
104 extern int errno;
105 
106 long
107 getcwd_(path, len)
108 char *path;
109 long len;
110 {
111 	char *p;
112 
113 	p = getcwd();
114 	if (p)
115 	{
116 		b_char(p, path, len);
117 		return(0L);
118 	}
119 	return((long)errno);
120 }
121