Board index » delphi » Using the getComputerName function

Using the getComputerName function


2003-07-05 05:30:49 PM
delphi131
Hi
I have been using the getComputerName function as shown in the code below,
which i found on the internet.
can anyone explain to me why there is a '-1' in this line:
Result := Copy(stationName,1,stationNameLen - 1)
I have tried it without and it still seems to work ok, but why is it there?
Thanks
Dave
function getStationName:string;
var
stationName : string;
stationNameLen : Dword;
begin
stationNameLen := 255;
SetLength(stationName, stationNameLen);
If GetComputerName(PChar(stationName), stationNameLen) Then
Result := Copy(stationName,1,stationNameLen - 1)
Else
Result := 'Unknown';
End;
 
 

Re:Using the getComputerName function

that is done to make sure you have at least 1 extra character in the resulting
string set to null with out it getting over written from the api call.
allot of api character fields require 1 extra byte then what it reports in
actual
length acquired after a call. this are null terminated strings and its always
good to
have 1 extra byte to work with other than what you indicate to the function
parameters.
you really should be doing -2 not 1 just incase for some reason your on a
system that may try to pass back Wide characters (Unicode) which uses
double null's
Dave writes:
Quote
Hi

I have been using the getComputerName function as shown in the code below,
which i found on the internet.
can anyone explain to me why there is a '-1' in this line:
Result := Copy(stationName,1,stationNameLen - 1)

I have tried it without and it still seems to work ok, but why is it there?

Thanks
Dave

function getStationName:string;
var
stationName : string;
stationNameLen : Dword;
begin
stationNameLen := 255;
SetLength(stationName, stationNameLen);
If GetComputerName(PChar(stationName), stationNameLen) Then
Result := Copy(stationName,1,stationNameLen - 1)
Else
Result := 'Unknown';
End;