9

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.

2 Answers 2

12

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.

Sign up to request clarification or add additional context in comments.

3 Comments

OK, that works nicely! Do I keep reading until Count<sizeOf(Buffer)?
Yes, just keep on reading until Count < Sizeof(Buffer). Note that buffer is not necessarily zero-terminated, so use e.g. a TMemoryStream to add the buffer to and finally add a #0 at the end, so you can read it as a string.
FWIW, although I answer questions here, I am mostly here to learn. Especially Objective-C, but also C, C++ and stuff like algorithms, etc.
4

try using a stream approach instead Read(buff)

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.