Although Jeroen doesn’t recommend it, I have done something like this about a year ago – just to learn how to do it. This is the code:
type
TTextFile = class
private type
TTextRecHelper = record helper for TTextRec
public
function GetTextFile: TTextFile;
procedure SetTextFile(const Value: TTextFile);
property TextFile: TTextFile read GetTextFile write SetTextFile;
end;
private var
FBuilder: TStringBuilder;
class function TextClose(var F: TTextRec): Integer; static;
class function TextIgnore(var F: TTextRec): Integer; static;
class function TextInput(var F: TTextRec): Integer; static;
class function TextOpen(var F: TTextRec): Integer; static;
class function TextOutput(var F: TTextRec): Integer; static;
procedure AppendString(const Value: string);
procedure AssignFile(var F: Text);
public
var F: Text;
constructor Create;
destructor Destroy; override;
function ToString: string; override;
end;
constructor TTextFile.Create;
begin
inherited Create;
FBuilder := TStringBuilder.Create();
AssignFile(F);
Rewrite(F);
end;
destructor TTextFile.Destroy;
begin
Close(F);
FBuilder.Free;
inherited Destroy;
end;
procedure TTextFile.AppendString(const Value: string);
begin
FBuilder.Append(Value);
end;
procedure TTextFile.AssignFile(var F: Text);
begin
FillChar(F, SizeOf(F), 0);
with TTextRec(F)do
begin
Mode := fmClosed;
BufSize := SizeOf(Buffer);
BufPtr := @Buffer;
OpenFunc := @TextOpen;
TextFile := Self;
end;
end;
class function TTextFile.TextClose(var F: TTextRec): Integer;
begin
Result := 0;
end;
class function TTextFile.TextIgnore(var F: TTextRec): Integer;
begin
Result := 0;
end;
class function TTextFile.TextInput(var F: TTextRec): Integer;
begin
F.BufPos := 0;
F.BufEnd := 0;
Result := 0;
end;
class function TTextFile.TextOpen(var F: TTextRec): Integer;
begin
if F.Mode = fmInput then
begin
F.InOutFunc := @TextInput;
F.FlushFunc := @TextIgnore;
F.CloseFunc := @TextIgnore;
end else
begin
F.Mode := fmOutput;
F.InOutFunc := @TextOutput;
F.FlushFunc := @TextOutput;
F.CloseFunc := @TextClose;
end;
Result := 0;
end;
class function TTextFile.TextOutput(var F: TTextRec): Integer;
var
AStr: AnsiString;
begin
SetLength(AStr, F.BufPos);
Move(F.BufPtr^, AStr[1], F.BufPos);
F.TextFile.AppendString(string(AStr));
F.BufPos := 0;
Result := 0;
end;
function TTextFile.ToString: string;
begin
Close(F);
result := FBuilder.ToString;
Rewrite(F);
end;
function TTextFile.TTextRecHelper.GetTextFile: TTextFile;
begin
Move(UserData[1], Result, Sizeof(Result));
end;
procedure TTextFile.TTextRecHelper.SetTextFile(const Value: TTextFile);
begin
Move(Value, UserData[1], Sizeof(Value));
end;
Example of how to use it according to your question:
tf := TTextFile.Create;
try
Writeln(tf.F, 'Result is: ', var1:8:2,' | ', var2:8:2,' |');
Caption := tf.ToString;
finally
tf.Free;
end;






Leave a comment