[net.sources] getenv

cmi@dartvax.UUCP (Theo Pozzy/R. Green) (07/07/84)

[]
Here is a version of the getenv() routine that works with the
COmputer Innovations C86 C compiler.  It only uses two library
functions,  both of which should exist in the standard library
(segread() and peek()).  Happy hacking!

-Theo Pozzy
...!decvax!dartvax!cmi (USENET)
cmi@dartmouth (CSNET)

------------ CUT HERE -------------------------------------------
#include "stdio.h"
#define TRUE 1
#define FALSE 0

main(argc,argv)				/* test program */
char **argv;
{
char *getenv(), *p;

p = getenv(*++argv);
if (p)
	printf("%s=%s\n",*argv,p);
else	printf("Environment variable '%s' not found\n",*argv);
}

char *getenv(v)
char *v;
{
struct {
	int cs, ss, ds, es;
} segreg;
char found = FALSE;
unsigned char *tp, *path, c;
unsigned int envseg, save_off;
int i, envoff;

segread(&segreg);			/* get segment registers */
envseg = peek(0x2c, segreg.cs);		/* get environment block segment address */

envoff = -1;

while(c = (peek(++envoff,envseg) & 0xff)) {
	tp = v;
	do {
		if (!*tp) {
			if (c == '=') found = TRUE;
			break;
		}
		if (*tp != c) break;
		++tp;
		c = peek(++envoff,envseg) & 0xff;
	} while(c);
	if (found) {			/* allocate some space and save it */
		save_off = envoff;
		for (i = 0; peek(++envoff,envseg) & 0xff; ++i);
		if (!(path = malloc(++i))) return NULL;
		envoff = save_off;
		tp = path;
		while (i--) *tp++ = peek(++envoff,envseg) & 0xff;
		return path;
	}
	while (c && (c = (peek(++envoff,envseg) & 0xff)));	/* skip rest of variable */
}

return NULL;

}