Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!uunet!bria!mike From: mike@bria.UUCP (mike.stefanik) Newsgroups: comp.unix.questions Subject: Re: Need help with subdirectories names Message-ID: <245@bria.UUCP> Date: 4 May 91 05:44:22 GMT References: <12746@uhccux.uhcc.Hawaii.Edu> Reply-To: uunet!bria!mike Organization: MGI Group International, Los Angeles, CA Lines: 94 In an article, denault@hale.ifa.hawaii.edu (Tony Denault) writes: >I have an application where the user can type in a directory. I would like >them to use short cuts names like ~username/whatever or $HOME/whatever. I >suppose the program will need to read these and expand them somehow. How >they get expanded is where I get confused. Assume that in reference to $HOME, you are talking about expansion of filenames like ~/this.file (the tilde alone specifies the $HOME path) >For the ~username, I was thinking of reading the /etc/passwd file, search >for the user name and determine their home directory. > >Is my thinking correct or am I missing something? Can anyone provide some >example code or routine that expands a relative or shortcut name into a full >pathname. Yes, your thinking is essentially correct. Here is a short program that does the tilde expansion. WARNING: Flames regarding the bletcherous hack that follows will be promptly flushed down /dev/null (read: get a life and write some code of your own, instead of reading mine! ;-) --- snip snip snip --------------------------------------------------------- #include #include #include char *explode(); main(argc,argv) int argc; char **argv; { while ( --argc ) puts(explode(*++argv)); return 0; } char *explode(path) char *path; { char *ptr, *getenv(); static char buf[256]; struct passwd *p, *getpwnam(); strncpy(buf,path,256); if ( *path++ == '~' ) { if ( *path == '/' || *path == '\0' ) { if ( (ptr = getenv("HOME")) == NULL ) return(buf); strcpy(buf,ptr); if ( strlen(path) > 0 ) { strcat(buf,"/"); strcat(buf,++path); } return(buf); } ptr = path; while ( isalnum(*++path) ) ; if ( *path != 0 ) *path++ = 0; if ( (p = getpwnam(ptr)) == NULL ) return(buf); strcpy(buf,p->pw_dir); if ( strlen(path) > 0 ) { strcat(buf,"/"); strcat(buf,path); } return(buf); } else return(buf); } ----- snip snip snip ------------------------------------------------------- Well, that's it, in all of it's ugly glory. Enjoy. -- Michael Stefanik, MGI Inc, Los Angeles | Opinions stated are never realistic Title of the week: Systems Engineer | UUCP: ...!uunet!bria!mike ------------------------------------------------------------------------------- If MS-DOS didn't exist, who would UNIX programmers have to make fun of?