environment variable expander

Mister Snufilupagus arnold at gatech.UUCP
Tue Sep 18 06:32:34 AEST 1984


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 at gatech	ARPA:	arnold%gatech.csnet at csnet-relay.arpa
UUCP: { akgua, allegra, hplabs, ihnp4 }!gatech!arnold

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



More information about the Comp.sources.unix mailing list