getting environment variables_(re)

Sun, 1 Dec 1996 17:37:07 +0100 (MET)


According to David Wooff:
> Greetings, fellow GPC users.  Despite trying the solutions suggested in the
> faq (http://agnes.dida.physik.uni-essen.de/~gnu-pascal/faq.html), I'm no
> nearer to getting an environment variable successfully into my program.
> For example, suppose I want to get the PATH environment variable into
> the program as a string that I can then work on?

That's strange.  When I try the program `EnvDemo' from the FAQ, it works
fine on my Linux box.  (The code I used is appended below just to make
sure that we are speaking about the same program.)

I suggest the following strategy to hunt the bug:

  * Control all intermediate results, e.g. p^ in StrPCopy and Src^ in
    StrPas.

  * Use the C `puts' output routine to check C strings:

      Procedure Puts ( S: CString ); C;
      ...
      Puts ( pName );
      Puts ( GetEnv ( pName ) );

BTW, thanks a lot for the GPC success story.  Things like this encourage
us to go on and fix the remaining bugs (e.g. `substr'). :-) :-)

    Peter

      e-mail:  peter.gerwinski@uni-essen.de
home address:  D\"usseldorfer Str. 35, 45145 Essen, Germany
         WWW:  http://agnes.dida.physik.uni-essen.de/~peter/

8< ----------------------------------------------------------------------------

Program EnvDemo;

type
  word = __unsigned__ integer;
  TString = string(256);        { Pascal string schema }
  CString = __cstring__;        { C style string }

{ Convert a "C" string to a "Pascal" string }
function StrPas(Src: CString): TString;
var
  S : TString;
begin
  S := '';
  if (Src <> NIL)
  then while ( (Src^ <> chr(0)) AND (length(S) < S.capacity)) do
  begin
    S := S + Src^;
    inc(Word(Src));
  end;
  StrPas := S;
end;

{ Convert a "Pascal" string to a "C" string }
function StrPCopy(Dest: CString; Src: String): CString;
var
  c: integer;
  p : CString;
begin
  p := Dest;
  for c:=1 to length(Src) do
  begin
    p^ := Src[c];
    inc(word(p));
  end;
  p^ := chr(0);
  StrPCopy := Dest;
end;

{ C library function prototype: char *getenv(const char *name); }
function GetEnv(name : CString): CString; C;

var
  pName: CString;

begin
  getmem(pName, 256);

  pName := StrPCopy(pName, 'PATH');
  writeln('Your PATH is: ', StrPas(GetEnv(pName)));

  freemem(pName, 256);
end.


Peter Gerwinski (peter@agnes.dida.physik.uni-essen.de)

HTML conversion by Lluís de Yzaguirre i Maura
Institut de Lingüística Aplicada - Universitat "Pompeu Fabra"
e-mail: de_yza@upf.es