From
Http://kingron.myetang.com/zsfunc0d.htm
(*//
Title: Making the best use of Pascal string types
Description: Unlike Pchar, string can hold #0 characters in it; Convert between sample files, memory stream strings
Design: Zswang
Date: 2002-01-25
Support: [Email protected]
//*)
Begin Source
function Stringtofile (mstring:string; Mfilename:tfilename): Boolean;
{return string saved to file succeeded}
Var
Vfilechar:file of Char;
I:integer;
Begin
{$I-}
AssignFile (Vfilechar, mfilename);
Rewrite (Vfilechar);
For I: = 1 to Length (mstring) do Write (Vfilechar, mstring[i]);
CloseFile (Vfilechar);
{$I +}
Result: = (IOResult = 0) and (mfilename <> ");
End {Stringtofile}
function filetostring (mfilename:tfilename): string;
{Returns a string loaded from a file}
Var
Vfilechar:file of Char;
Vchar:char;
Begin
Result: = ';
{$I-}
AssignFile (Vfilechar, mfilename);
Reset (Vfilechar);
While not Eof (Vfilechar) does begin
Read (Vfilechar, Vchar);
Result: = result + Vchar;
End
CloseFile (Vfilechar);
{$I +}
End {filetostring}
function streamtostring (mstream:tstream): string;
{Convert memory flow to string}
Var
I:integer;
Begin
Result: = ';
If not Assigned (mstream) then Exit;
SetLength (Result, mstream.size);
For I: = 0 to Pred (mstream.size) do try
Mstream.position: = I;
Mstream.read (RESULT[SUCC (I)], 1);
Except
Result: = ';
End
End {streamtostring}
function Stringtostream (mstring:string; Mstream:tstream): Boolean;
{Returns whether the string was successfully saved to the memory stream}
Var
I:integer;
Begin
Result: = True;
Try
Mstream.size: = 0;
Mstream.position: = 0;
For I: = 1 to Length (mstring) does Mstream.write (Mstring[i], 1);
Except
Result: = False;
End
End {Stringtostream}
End Source
Begin Demo
Procedure Tform1.button1click (Sender:tobject);
Var
Vmemorystream:tmemorystream;
Begin
Memo1.text: = filetostring (' C:\WINDOWS\Desktop\1.txt ');
Vmemorystream: = tmemorystream.create;
Try
Memo1.Lines.SaveToStream (Vmemorystream);
Memo2.text: = streamtostring (Vmemorystream);
Finally
Vmemorystream.free;
End
End
Procedure Tform1.button2click (Sender:tobject);
Var
Vmemorystream:tmemorystream;
Begin
Stringtofile (Memo2.text, ' C:\WINDOWS\Desktop\1.txt ');
Vmemorystream: = tmemorystream.create;
Try
Stringtostream (Memo2.text, Vmemorystream);
Vmemorystream.position: = 0;
Memo1.Lines.LoadFromStream (Vmemorystream);
Finally
Vmemorystream.free;
End
End
End Demo
Http://www.delphitop.com/html/zifuchuan/1711.html
How Delphi converts a file stream to a string (string to flow, string to file, and to each other)