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
micappelAsked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
RBertoraConnect With a Mentor Commented:
you need to do something like this:



var
   Tmp : pointer

   Tmp := pointer(txt);
   YourFileStream.Write(Tmp^, Length(txt));

or declare similar:

txt : String[20]

Rob ;-)
0
 
MadshiCommented:
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.
0
 
micappelAuthor Commented:
Thanks!

Then, how do i read it back? Do i have to reference it as a pointer there to?
0
 
RBertoraCommented:
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 ;-)

0
All Courses

From novice to tech pro — start learning today.