[Lazarus] Cloning standard output to text file

leledumbo leledumbo_cool at yahoo.co.id
Sun May 6 23:39:02 CEST 2018


> Sorry, I fail to see how I can use this with writeln to write to *both* 
> output and file at the same time. Maybe I miss something :-? 

{$mode objfpc}{$H+}

uses
  Classes,SysUtils,StreamIO;

type
  TDoubleStream = class(TFileStream)
  private
    FStdOut: TextFile;
  public
    constructor Create(const AFileName: string; Mode: Word);
    destructor Destroy; override;
    function Write(const Buffer; Count: longint): longint; override;
  end;

constructor TDoubleStream.Create(const AFileName: string; Mode: Word);
begin
  inherited Create(AFileName,Mode);
  AssignFile(FStdOut,''); // empty string = stdout
  Rewrite(FStdOut);
end;

destructor TDoubleStream.Destroy;
begin
  CloseFile(FStdOut);
  inherited Destroy;
end;

function TDoubleStream.Write(const Buffer; Count: longint): longint;
var
  p: PChar;
begin
  Result := inherited Write(Buffer, Count);
  p := PChar(@Buffer); // safe assumption for standard output, I guess?
  while Count > 0 do begin
    System.Write(FStdOut,p^);
    Inc(p);
    Dec(Count);
  end;
end;

var
  ds: TStream;
begin
  ds := TDoubleStream.Create('log.txt', fmCreate or fmOpenWrite);
  try
    AssignStream(Output,ds);
    Rewrite(Output);
    WriteLn('Hello!');
  finally
    ds.Free;
  end;
end.



--
Sent from: http://free-pascal-lazarus.989080.n3.nabble.com/


More information about the Lazarus mailing list