read till EOF from stdin

kdevel kdevel at vogtner.de
Fri Dec 11 02:31:24 UTC 2020


Currently as a workaround I read all the chars from stdin with

    import std.file;
    auto s = cast (string) read("/dev/fd/0");

after I found that you can't read from stdin. This is of course
non-portable Linux only code. In perl I frequently use the idiom

    $s = join ('', <>);

that corresponds to D's

    import std.stdio;
    import std.array;
    import std.typecons;
    auto s = stdin.byLineCopy(Yes.keepTerminator).join;

which alas needs an amazing amount of import boilerplate. BTW why 
does
byLine not suffice in this case? Then there is a third way of 
reading
all the characters from stdin:

    import std.stdio;
    import std.array;
    auto s = cast (string) stdin.byChunk(1).join;

This version behaves correctly if Ctrl+D is pressed anywhere after
the program is started. This is no longer the case a if larger 
chunk
is read, e.g.:

    auto s = cast (string) stdin.byChunk(4).join;

As strace reveals the resulting program sometimes reads twice zero
characters before it terminates:

    read(0, a                                         <-- A, return
    "a\n", 1024)                    = 2
    read(0, "", 1024)                       = 0       <-- ctrl+d
    read(0, "", 1024)                       = 0       <-- ctrl+d

Any comments or ideas?



More information about the Digitalmars-d-learn mailing list