Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read program STDIN in Delphi

Tags:

stdin

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:

  • putting the read part into a loop with eof as a condition - somehow causing an infinite loop
  • writing a loop to keep reading until strlen(buff) is 0 - it exits the second time for some reason
  • reading stuff ever 0.5 seconds (I was thinking about asynchronous writes to stdin), this failed as well

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

like image 679
Christian Avatar asked Aug 14 '11 01:08

Christian


1 Answers

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.

like image 106
Rudy Velthuis Avatar answered Oct 12 '22 06:10

Rudy Velthuis