Path: utzoo!utgpu!news-server.csri.toronto.edu!rutgers!uwm.edu!wuarchive!udel!princeton!phoenix.Princeton.EDU!pfalstad From: pfalstad@phoenix.Princeton.EDU (Paul John Falstad) Newsgroups: comp.unix.programmer Subject: Re: getting the current working directory Message-ID: <5195@idunno.Princeton.EDU> Date: 11 Jan 91 08:10:37 GMT References: <42380@ut-emx.uucp> Sender: news@idunno.Princeton.EDU Distribution: usa Organization: Princeton University, Princeton, New Jersey Lines: 76 In article <42380@ut-emx.uucp> pefv700@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@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