getting the current working directory
Paul John Falstad
pfalstad at phoenix.Princeton.EDU
Fri Jan 11 19:10:37 AEST 1991
In article <42380 at ut-emx.uucp> pefv700 at perv.pe.utexas.edu writes:
>According to my SunOS man page on getwd(3), getwd(buf) will put the absolute
>path of the current working directory in buf UNLESS there is an error, in
>which case buf contains some message. The problem is, you don't know if you
>got the directory name or the message.
Yes, you do. If there is an error, getwd returns NULL. Otherwise it
returns the address of the buffer.
Here is a version of getwd I wrote for zsh. I'd be interested in what
people think of it. I needed a version that didn't fork(), and was
having problems with the Sun getwd().
char *getwd(void)
{
static char buf0[MAXPATHLEN];
char buf3[MAXPATHLEN],*buf2 = buf0+1;
struct stat sbuf;
struct direct *de;
DIR *dir;
ino_t ino = -1;
dev_t dev = -1;
buf2[0] = '\0';
buf0[0] = '/';
for(;;) {
if (stat(".",&sbuf) < 0) {
chdir(buf0);
return NULL;
}
ino = sbuf.st_ino;
dev = sbuf.st_dev;
if (stat("..",&sbuf) < 0) {
chdir(buf0);
return NULL;
}
if (sbuf.st_ino == ino && sbuf.st_dev == dev) { /* we're done */
chdir(buf0);
return strdup(buf0);
}
dir = opendir("..");
if (!dir) {
chdir(buf0);
return NULL;
}
chdir("..");
readdir(dir); readdir(dir);
while (de = readdir(dir))
if (de->d_fileno == ino) { /* find file with matching inode */
lstat(de->d_name,&sbuf);
if (sbuf.st_dev == dev)
goto match;
}
rewinddir(dir);
readdir(dir); readdir(dir);
while (de = readdir(dir)) {
lstat(de->d_name,&sbuf);
if (sbuf.st_dev == dev) /* find file with matching device # */
goto match;
}
closedir(dir);
return NULL;
match:
strcpy(buf3,de->d_name);
if (*buf2)
strcat(buf3,"/");
strcat(buf3,buf2);
strcpy(buf2,buf3);
closedir(dir);
}
}
--
Paul Falstad, pfalstad at phoenix.princeton.edu PLink:HYPNOS GEnie:P.FALSTAD
"We could nuke Baghdad into glass, wipe it with Windex, tie fatback on
our feet and go skating." - Air Force Times columnist Fred Reed
More information about the Comp.unix.programmer
mailing list