Link to home
Start Free TrialLog in
Avatar of micappel
micappel

asked on

Writing strings to TFileStream?

How do i write a string into a TFileStream?

I have an initiated filestream (fsKeyStream) var passed to a method in a key object containing some strings i need to save.

procedure TKey.SaveToFile(var fs : TFileStream );
begin
  fs.write(Title, sizeof(Title);
  ..
  ..
end;

procedure TKeyList.SaveToFile;
var
  keystream: TFileStream;
begin
  keystream := TFileStream.Create(...
  .. go through list items and...
    TKey(Items[index]).SaveToFile( keystream );
...
end;

The strings in Key contains the right data when i debug, and the resulting file has the right amount om items saved to it, but the saved strings are just empty..

What do i do wrong?

Micappel
ASKER CERTIFIED SOLUTION
Avatar of RBertora
RBertora
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Madshi
Madshi

Rob is right. This is the same in shorter form...   :-)

  YourFileStream.Write(pchar(txt)^, Length(txt));

If you want to write more than one string into a file you should either write a #$D#$A behind each string (then you have a text file with line breaks after each string) or you should write the length of the string in front of the characters (then you have a binary file). A text file is perhaps nicer, but a binary file is faster to read.

Text file:

  YourFileStream.Write(pchar(txt + #$D#$A)^, Length(txt) + 2);

Binary file:

var i1 : integer;
 
  i1 := Length(txt);
  YourFileStream.Write(i1, 4);
  YourFileStream.Write(pchar(txt)^, i1);

Regards, Madshi.
Avatar of micappel

ASKER

Thanks!

Then, how do i read it back? Do i have to reference it as a pointer there to?
I think you do something like this:

you can declare something like

Buffer : String[200];

 Read(Buffer,200);

or

BufferPointer : Pointer;

BufferPointer := allocmem(200);
Read(bufferPointer,200);

But I never have used filestreams my comments are purely theoretical... so perhaps madshi can confirm.
Rob ;-)