[net.sources] environment variable expander

arnold@gatech.UUCP (Mister Snufilupagus) (09/17/84)

Here is a useful function which I wrote some time ago.  It will expand
environment variables inside file names.  This is particularly useful
for any screen editors or text formatters you may happent to be writing...
(That's what I used it for...)

An environment variable starts with a dollar sign.  To get a literal
dollar sign, escape it with a \.

---------------- cut here --------------------
cat > expandenv.c << 'End of expandenv.c'
/* expand_env --- expand environment variables in file names */

#include <stdio.h>

char *expand_env (file)
register char *file;		/* file name to be expanded */
{
	register int i, j, k;	/* indices */
	char *getenv ();
	char var[BUFSIZ];		/* variable name */
	char *val;			/* value of environment variable */
	static char buf[BUFSIZ * 2];	/* expanded file name, static */

	i = j = k = 0;
	while (file[i] != '\0')
	{
		if (file[i] == '\\')
		{
			if (file[i+1] == '$')
			{
				buf[j++] = file[++i];	/* the actual $ */
				i++;	/* for next time around the loop */
			}
			else
				buf[j++] = file[i++];	/* the \ */
		}
		else if (file[i] != '$')	/* normal char */
			buf[j++] = file[i++];
		else			/* environment var */
		{
			i++;	/* skip $ */
			k = 0;
			while (file[i] != '/' && file[i] != '\0')
				var[k++] = file[i++];	/* get var name */
			var[k] = '\0';

			if ((val = getenv (var)) != NULL)
				for (k = 0; val[k] != '\0'; k++)
					buf[j++] = val[k];
					/* copy val into file name */
			/* else
				var not in enviroment; leave file
				name alone, multiple slashes are legal */
		}
	}
	buf[j] = '\0';

	return (buf);
}
End of expandenv.c
exit
-- 
Arnold Robbins
CSNET: arnold@gatech	ARPA:	arnold%gatech.csnet@csnet-relay.arpa
UUCP: { akgua, allegra, hplabs, ihnp4 }!gatech!arnold

Can you tell me how to get, how to get to Sesame Street?

ron@trsvax.UUCP (09/21/84)

> Can you tell me how to get, how to get to Sesame Street?

:-) Yes, go down three functions and turn to the right. Do not pass GO. :-)