Code to get all environment variables

Deewiant deewiant.doesnotlike.spam at gmail.com
Mon Jun 12 02:43:54 PDT 2006


Something like this should really be in Phobos, and unless it's already there, Ares.

I figured I'd post what I coded to accomplish this task. It should work in
Windows and any Posix platform - I tested it only on Windows XP and Cygwin,
though, but it ought to be alright.

The Windows code uses the ASCII, not UTF-16, versions of the functions, since
I'm not comfortable messing around with different encodings - I'm not sure
whether it would be smarter to make the Posix version convert ASCII to wchars or
the Windows code to convert UTF-16 to chars.

I was never good with pointer twiddling, so I couldn't figure out a way to use
the same code for both versions. Feel free to do whatever you want with it, I
release it in the public domain.

--

version (Windows) {
	pragma (lib, "kernel32");

	extern (Windows) {
		void * GetEnvironmentStringsA();
		bool   FreeEnvironmentStringsA(char**);
	}

	char[][char[]] environment() {
		char ** env = cast(char**)GetEnvironmentStringsA();
		scope (exit) FreeEnvironmentStringsA(env);

		char[][char[]] arr;

		for (char * str = cast(char*)env; *str; ++str) {
			char[] key   = new char[20],
			       value = new char[40];

			size_t i;

			while (*str != '=') {
				key[i++] = *str++;

				if (i == key.length)
					key.length = 2 * key.length;
			}
			key.length = i;

			i = 0;
			++str;

			while (*str) {
				value[i++] = *str++;

				if (i == value.length)
					value.length = 2 * value.length;
			}
			value.length = i;

			arr[key] = value;
		}

		return arr;
	}
} else {
	pragma (msg, "If this is not a Posix-compliant platform, trying to access
environment\nvariables will probably cause an access violation and thereby a
crash.");

	extern (C) extern char ** environ;

	char[][char[]] environment() {
		char[][char[]] arr;

		for (char ** p = environ; *p; ++p) {
			char[] key   = new char[20],
			       value = new char[40];

			size_t i;
			char * str = *p;

			while (*str != '=') {
				key[i++] = *str++;

				if (i == key.length)
					key.length = 2 * key.length;
			}
			key.length = i;

			i = 0;
			++str;

			while (*str) {
				value[i++] = *str++;

				if (i == value.length)
					value.length = 2 * value.length;
			}
			value.length = i;

			arr[key] = value;
		}

		return arr;
	}
}



More information about the Digitalmars-d-announce mailing list