D (Tango) Read all standard input and assign it to a line

In D, how can I read all standard input and assign it to a string (using the Tango library)?

+5
source share
2 answers

Another probably more effective way to dump Stdin content would be something like this:

module dumpstdin;

import tango.io.Console : Cin;
import tango.io.device.Array : Array;
import tango.io.model.IConduit : InputStream;

const BufferInitialSize = 4096u;
const BufferGrowingStep = 4096u;

ubyte[] dumpStream(InputStream ins)
{
    auto buffer = new Array(BufferInitialSize, BufferGrowingStep);
    buffer.copy(ins);
    return cast(ubyte[]) buffer.slice();
}

import tango.io.Stdout : Stdout;

void main()
{
    auto contentsOfStdin
        = cast(char[]) dumpStream(Cin.stream);

    Stdout
        ("Finished reading Stdin.").newline()
        ("Contents of Stdin was:").newline()
        ("<<")(contentsOfStdin)(">>").newline();
}

Some notes:

  • A second parameter is needed for the array; if you omit it, the array will not grow in size.
  • I used 4096, since this is usually the size of the memory page.
  • dumpStream a ubyte[], char[] UTF-8, Stdin. , - , char[], , - . , char[] .
  • copy - OutputStream, InputStream .
+1

http://www.dsource.org/projects/tango/wiki/ChapterIoConsole:

import tango.text.stream.LineIterator;

foreach (line; new LineIterator!(char)(Cin.stream))
     // do something with each line

,

auto line = Cin.copyln();
+2

All Articles