[fpc-devel] Running programs with output redirection

Andrew Haines AndrewD207 at aol.com
Sat Jul 16 23:01:29 CEST 2011


On 07/16/11 16:37, Hans-Peter Diettrich wrote:
> There seems to exist an issue with (output) redirection, when I try to
> run an external program from code. What I want to achieve is this:
> 
> In a Win32 console I can run
>>diff -r dir1 dir2 > diff.txt
> 
> When I use e.g. Exec('diff', args), diff complains about an excess
> argument, it works when "> diff.txt" is removed. With other functions I
> had less luck (ExecuteProcess, CreateProcess...), no output at all.
> 
> Now I assume that output redirection is a shell feature, not available
> in direct invocation of an external program. Right?
> 
> Does there exist a simple way to run "diff", and to redirect its output
> into an file? A batch file? Platform independence would be nice, of course.
> 
> DoDi
> 
> _____

The best way I know is described here:
http://wiki.lazarus.freepascal.org/Executing_External_Programs#How_to_redirect_output_with_TProcess

something like the following (not tested)

function RunCommandAndDirectOutput(ACommand, AArgs, AOutName: String):
Integer;
var
 proc: TProcess;
 data: TFileStream;
 buffer: array [0..511] of byte;
 count: Integer;

begin
  proc := TProcess.Create(nil);
  proc.commandline := ACommand + ' ' + AArgs;
  proc.options := [pousepipes];

  data := TFileStream.Create(AOutName, fmcreate or fmwrite);

  proc.Execute;
  while proc.running or proc.output.numbytesavailable > 0 do
  begin
    count := proc.output.numbytesavailable;
    if count > 512 then
      count := 512;
    count := proc.output.read(buffer, count);
    data.write(buffer, count);
  end;
  Result := Proc.ExitStatus;
  proc.free;
  data.free;

end;

usage:

RunCommandAndDirectOutput('diff', '-r dir1 dir2', 'diff.txt');

Regards,

Andrew Haines





More information about the fpc-devel mailing list