Yes, I know how to deal with text files, with the classic approach or with TStringList methods. In my context, I want to use streams because I need to save text files both in files and in memory. Streams, as well known, allow this type of needs to be managed in a unified way.
Since TStream.WriteAnsiString is virtual, while TStream.ReadAnsiString is not (why???), I can't override them to change their behavior. So, using class helpers, I devised this simple solution to manage purely textual (ansi) files with streams:
program project1;
uses
Classes;
type
{ TStreamHelper }
TStreamHelper=class helper for TStream
function ReadText:string;
procedure WriteText(const Text : string);
end;
var
FileStream : TFileStream;
{ TStreamHelper }
function TStreamHelper.ReadText:string;
var
P : PByte;
begin
Result:='';
SetLength(Result,Size);
Position:=0;
ReadBuffer(Pointer(Result)^,Size);
P:=Pointer(Result)+Size;
P^:=0;
end;
procedure TStreamHelper.WriteText(const Text : string);
begin
Position:=0;
WriteBuffer(Pointer(Text)^,Length(Text));
end;
begin
//write test
FileStream:=TFileStream.Create('file.txt',fmCreate);
try
FileStream.WriteText('aaabbbccc');
finally
FileStream.Free;
end;
//read test
FileStream:=TFileStream.Create('file.txt',fmOpenRead);
try
writeln(FileStream.ReadText);
finally
FileStream.Free;
end;
readln;
end.