Need help with subdirectories names
mike.stefanik
mike at bria.UUCP
Sat May 4 15:44:22 AEST 1991
In an article, denault at 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 <stdio.h>
#include <ctype.h>
#include <pwd.h>
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?
More information about the Comp.unix.questions
mailing list