We know, in many cases, the Windows API function requires a buffer, for example, API GetTemppath for obtaining a temporary directory as an example. This function requires a buffer to store the returned directory name, and many people code (including many masters and borland) Experts) written this:
Function GetTempdirectory:
String;
VAR
Tempdir:
Array [0..255]
Of char;
Begin
GetTemppath (255, @Tempdir);
Result: = STRPAS (Tempdir);
END;
Obviously, if the name of the temporary directory exceeds 256, the buffer overflow will occur, the data obtained is not complete, in fact, the full path of the temporary directory is likely to exceed 256, and the long text name of Windows refers to this directory or file. Significance of name, not Full Path
Name limit! So how to use this function?
Generally, the function of the buffer is required, we need to call twice! The first call is to obtain the length of the buffer, and then the second time is the real call. Take the above as an example, the true correct way should be:
Procedure TForm1.Button1Click (Sender: Tobject); Var mybuf: array of char; len: integer; begin len: = getTemppath (0, nil); setlength (mybuf, len); getTemppath (Len 1, pchar (mybuf)) SHOWMESSAGE (PCHAR (MyBUF)); END; other similar functions such as getComputername, etc., should be used so. Also pay attention to the use of PCHAR!