[fpc-pascal] Setting environment variables on Unix/Linux?
Reinier Olislagers
reinierolislagers at gmail.com
Thu Nov 17 13:13:17 CET 2011
Hi list,
It seems FPC allows one to retrieve environment variables on Linux/Unix
(GetEnvironmentVariable) but not to set them.
Is that correct?
Some digging:
Setting environment variables on Unix with gnu libc:
http://www.gnu.org/s/libc/manual/html_node/Environment-Access.html#Environment-Access
int setenv (const char *name, const char *value, int replace)
The setenv function can be used to add a new definition to the
environment. The entry with the name name is replaced by the value
‘name=value’.
If replace = 1, replace existing variable.
This one seems not to be present in FPC libc code
Maybe something like (taken from netware source\rtl\netwlibc\libc.pp):
function setenv(_para1:Pchar; _para2:Pchar;
_para3:longint):longint;cdecl;external clib name 'setenv';
remove environment variable:
int unsetenv (const char *name)
The function return -1 if name is a null pointer, points to an empty
string, or points to a string containing a = character. It returns 0 if
the call succeeded.
also adapted from netware
function unsetenv(name:Pchar):longint;cdecl;external clib name 'unsetenv';
Can I just do something like (air code):
Should a c int be an int or a longint or something like cint?
Thanks, Reinier
{$IFDEF Unix}
//should a c int be an int or a longint or something like cint?
function setenv(name:Pchar; value:Pchar;
replace:longint):longint;cdecl;external clib name 'setenv';
function unsetenv(name:Pchar):longint;cdecl;external clib name 'unsetenv';
function SetEnvironmentVariable(name:string; value:string):boolean;
// Set environment variable; if empty string given, remove it.
// Done for Windows compatibility as in Unixy environments,
// blank environment variables actually may exist.
begin
result:=false; //assume failure
if Name:='' then
begin
// Assume user wants to remove variable.
if unsetenv(PChar(name))=0 then result:=true;
end
else
begin
// Non empty so set the variable
if setenv(PChar(name), PChar(value), 1)=0 then result:=true;
end;
end;
{$ENDIF}
More information about the fpc-pascal
mailing list