program test;
{$mode objfpc}{$H+}
uses
sysutils, classes, baseunix;
var
hs : thandlestream; // renamed to hs to indicate HandleStream (and not FileStream)
oldoutputhandle : thandle;
olderrorhandle : thandle;
i, j : longint;
e : array[1..4] of longint;
c : array[1..4] of char = 'abcd'; // additional buffer for testing
s : string; // additional string s for an additional example
begin
// corrected your loop to avoid using wrong indices
for i := low(e) to high(e) do e[i] := 2;
// duplicate original stdout & stderr handles for safekeeping
oldoutputhandle := fpdup(textrec(stdout).handle);
olderrorhandle := fpdup(textrec(stderr).handle);
// Create a handlestream for stdoutput
hs := thandlestream.create(stdoutputhandle);
// copy/assign handlestream's handle to stderrorhandle and stdoutputhandle
fpdup2(hs.handle, stderrorhandle);
fpdup2(hs.handle, stdoutputhandle);
// write values of j to /stdout/
for j := 1 to 30
do write(j); // Q: where is this going? A: to stdout
writeln;
// additional example that uses handlestream to write something to stdout
for j := 1 to 30 do
begin
s := j.ToString;
hs.write(s[1], Length(s));
end;
writeln;
// there is no use calling hs.size and hs.position as afaik all data written
// to handlestream is directly emitted to stdout as handlestream is not buffered.
// Handlestream is initialized in such a way that it simply wraps around
// stdout so that you can use stream class functionality to write to stdout.
writeln('hs.position : ', hs.position);
hs.position := 0;
writeln('hs.position : ', hs.position);
writeln('hs.size : ', hs.size);
// the following code-line in your source puzzled me a bit as it did not
// output what I expected. It should output 4 times a decimal value of 2
// (note: not the ascii representation of the value/number 2) and the
// length of the number of bytes written (which is 4) to the terminal.
// Instead, it only printed the number 4 for me.
// From that I have to conclude that either the terminal is smart enough to
// ignore the 4 decimal values of 2 or the write implementation filters out
// any characters that are not in "printable" range.
// writeln(hs.write(e, 4));
// In order to see the same line in a "working" manner, i've adapted it to
// emit characters instead and which indeed show the expected result.
writeln(hs.write(c, length(c)));
// corrected your loop to avoid using wrong indices and added some proper
// output that imho makes more sense.
for i := low(e) to high(e)
do writeln('e[', i, '] = ', e[i]);
hs.free;
// restore original handles
fpdup2(oldoutputhandle, textrec(stdout).handle);
fpdup2(olderrorhandle , textrec(stderr).handle);
end.