Christian
Christian

Reputation: 28124

Read program STDIN in Delphi

I have the following batch script:

dir | myapp.exe

And the program has this source (more or less):

procedure TForm1.FormCreate(Sender: TObject);
var buff: String;
begin
  Read(buff);
  Memo1.Lines.Text:=buff;
end;

And the output in the memo is:

Volume in drive C has no label.

I tried:

By the way, running the program directly, without stdin data, causes an EInputOutput exception (I/O Error) code 6.

Upvotes: 9

Views: 3908

Answers (2)

Rudy Velthuis
Rudy Velthuis

Reputation: 28806

GUI apps don't have a stdin, stdout or stderr assigned automatically. You can do something like:

procedure TForm1.FormCreate(Sender: TObject);
var
  Buffer: array[0..1000] of Byte;
  StdIn: TStream;
  Count: Integer;
begin
  StdIn := THandleStream.Create(GetStdHandle(STD_INPUT_HANDLE));
  Count := StdIn.Read(Buffer, 1000);
  StdIn.Free;
  ShowMessageFmt('%d', [Count]);
end;

If you do

dir *.pas | myapp.exe

You'll see a messagebox with a number > 0, and if you do:

myapp.exe

You'll see a messagebox with 0. In both cases, the form will be shown.

Upvotes: 12

Yahia
Yahia

Reputation: 70369

try using a stream approach instead Read(buff)

InputStream := THandleStream.Create(GetStdHandle(STD_INPUT_HANDLE));

Upvotes: 4

Related Questions