Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Nelp needed using PChar

Status
Not open for further replies.

topcat01

Programmer
Jul 10, 2003
83
GB
Hi,

I have searched the forum and google and wondered if anyone can answer the following:

This is my code for reading a pchar null terminated string from a file which seems to work ok, in this example I know the string is 16 bytes long.

Code:
  var
    CurrentFile : TFilestream;
    MyName : PChar;
              
    CurrentFile.ReadBuffer(MyName,16);
    Add('      Name: '+PChar(@MyName));

My question is if I don't know how long the string is can I use pchar to read a string from a file until it reads the null, if yes how?

I tried "CurrentFile.ReadBuffer(MyName,255);" (as 255 is max size of name) but the program crashes prob because the total filesize was only 50 bytes in size.

Hope I have made myself clear ?
 
PChar is a pointer to a character. It's useful for reading null-terminated strings. The thing is though, you have to allocate space for it first, and work with that space. You can either do it from a Pascal string like I do in the code below (that's how I usually handle Windows API calls that want PChar types for input/output), or from an array of characters.

The output of this code to the file will be

Code:
TEST STRING#0

To find the length of a null-terminated string, you have to load it into the buffer and then search for #0.

Code:
var
  outfile: file;
  outPString: PChar;
  outstring: string;
begin
  AssignFile(outfile, 'TEST.FIL');
  rewrite(outfile, 1);
  outstring := 'TEST STRING' + #0;
  outPString := PChar(@outstring[1]);
  blockwrite(outfile, outPString^, length(Outstring));
  Closefile(outfile);
end;

Not sure that explains much, but hope it helps.

----------
Measurement is not management.
 
Thanks for the reply glenn.

I've been looking at this for too long.

I read into an array and searched for null and all works now.
 
Keep in mind that a TString IS an array.
array [1..length] of char; (byte[0] contains the length, up to 255)
Does NOT apply to THugeString.



Roo
Delphi Rules!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top