Saving and Loading strings in stream the Delphi 2009 way

Refresh Lately, I had a simple task to save and load some short strings in file.
The quickest and fastest way is to do it with streams (TFileStream or TMemoryStream).

Because in Delphi 2009 string type strings are Unicode so they are also double byte sized than in previous Delphi strings.
So you need to be very strict to write exact BYTES of the string, not characters, because character size is now 2 Bytes!

For Writing String to any stream use these Functions :


procedure WriteStreamInt(Stream : TStream; Num : integer);
begin
 Stream.WriteBuffer(Num, SizeOf(Integer));
end;

procedure WriteStreamStr(Stream : TStream; Str : string);
var
 StrLen : integer;
begin
 StrLen := Length(Str); //All Delphi versions compatible
 WriteStreamInt(Stream, StrLen);
 Stream.WriteBuffer(Pointer(Str)^, StrLen * SizeOf(Char)); //All Delphi versions compatible
end;

The reading of string shoud be also exact with character size in mind. Because you can read only half of string:


function ReadStreamInt(Stream : TStream) : integer;
begin
Stream.ReadBuffer(Result, SizeOf(Integer));
end;

function ReadStreamStr(Stream : TStream) : string;
var
StrLen : integer;
TempStr : string;
begin
TempStr := '';
StrLen := ReadStreamInt(Stream);
if StrLen > -1 then
begin
SetLength(TempStr, StrLen);
//Here you should also check the character size
//Reading Bytes!
Stream.ReadBuffer(Pointer(TempStr)^, StrLen * SizeOf(Char));
result := TempStr;
end
else Result := '';
end;

Then you can write functions for writing and loading strings for example:


function SaveToDFile( FileName: String; sDescr : string; ) : boolean;
var  MemStr: TMemoryStream;
begin
MemStr:= TMemoryStream.Create;
try
try
WriteStreamStr( MemStr, sDescr );
MemStr.SaveToFile(FileName);
result := True;
except
on E:EWriteError do result := False;
end;
finally
MemStr.Free;
end;
end;

function LoadFromDFile( FileName: String; var sDescr : string; ) : boolean;
var MemStr: TMemoryStream;
begin
MemStr:= TMemoryStream.Create;
try
try
MemStr.LoadFromFile(FileName);
sDescr := ReadStreamStr( MemStr );
result := True;
except
on E:EReadError do result := False;
end;
finally
MemStr.Free;
end;
end;

Hope it helps some.

Advertisements

5 responses to “Saving and Loading strings in stream the Delphi 2009 way

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

%d bloggers like this: