开发者

Read program STDIN in Delphi

I have the following batch script:

dir | myapp.exe

An开发者_C百科d 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.


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.


try using a stream approach instead Read(buff)

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜