In the D language how I can read all standard input and assign it to a string (with Tango library) ?
+2
A:
Copied straight from 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
If only 1 line is required, use
auto line = Cin.copyln();
KennyTM
2010-03-06 18:07:59
Instead of taking individual lines, how can I take everything in a single string
Sebtm
2010-03-06 18:31:25
@sebtm: Concatenate them. (and what if the user `yourprogram < /dev/urandom`? You'll get an infinitely long string.)
KennyTM
2010-03-06 18:37:51
@KennyTM: Ok is correct. But in my case is only `cat smalltextfile.txt | myprogram`.
Sebtm
2010-03-06 19:07:41
+1
A:
Another, probably more efficient way, of dumping the contents of Stdin 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:
- The second parameter to Array is necessary; if you omit it, Array will not grow in size.
- I used 4096 since that's generally the size of a page of memory.
dumpStream
returns aubyte[]
becausechar[]
is defined as a UTF-8 string, which Stdin doesn't necessarily need to be. For example, if someone piped a binary file to your program, you would end up with an invalidchar[]
that could throw an exception if anything checks it for validity. If you only care about text, then casting the result to achar[]
is fine.copy
is a method on theOutputStream
interface that causes it to drain the providedInputStream
of all input.
DK
2010-03-07 04:27:14