Piping from terminal into D program

WebFreak001 d.forum at webfreak.org
Sat Sep 4 18:20:51 UTC 2021


On Saturday, 4 September 2021 at 15:41:51 UTC, eXodiquas wrote:
> Hello everyone,
>
> I created a small little D program that reads in a string from 
> the command line and shuffles the letters of the nouns a bit 
> around. This is pretty straight forward, but what I see now 
> happening is a bit strange, at least for me.
>
> I am reading the args out of the main function arguments.
>
> ```d
> void main(string[] args) {
>   args.writeln();
> }
> ```
>
> this works fine whenever I call the program like 
> `./nounscramble "Hello, my name is Earl!"` the string shows up 
> in `args[1]`. But when I call `echo "Hello, my name is Earl!" | 
> ./nounscramble` it does not show up in the args array, the only 
> thing showing up is the name of the executable (which is 
> expected).
>
> My question is now, can someone explain what I am doing wrong? 
> Maybe I misunderstood the pipe in Linux systems and it is 
> obvious for someone who knows how this works exactly, or maybe 
> D works differently with pipes and I havn't found the correct 
> documentation.
>
> Thanks in advance. :)
>
> eXodiquas

to extend on Brian Tiffin's reply, you can read from the standard 
input stream (the data piped to your program) using std.stdio's 
`stdin`

Example:

```d
import std.stdio;
foreach (line; stdin.byLine)
     writeln("got input line: ", line);
// IMPORTANT: the line buffer is reused (it's a char[], not a 
string), so if you want to store it in a variable outside the 
foreach, use .idup to make it a string (that is not changed when 
leaving the loop)
```

or

```d
import std.stdio;
foreach (chunk; stdin.byChunk(1024))
     writeln("got input chunk: ", cast(char[])chunk);
// same warning as above, don't case to string (that's unsafe and 
wouldn't be allowed in @safe code, but casting to char[] is safe, 
as it explicitly says it can be changed)
```

or

```d
import std.stdio;
ubyte[1024] buffer;
auto part = cast(char[])stdin.rawRead(buffer[]);
writeln("got part: ", part);
// this is the lower level equivalent of the byChunk above, it's 
just doing a single step instead of multiple chunks, so you 
control when it is changed.
// a slice of this buffer (which is what the return value is) 
needs to be .idup'd to be persisted outside the lifetime of the 
`buffer` variable
```


More information about the Digitalmars-d-learn mailing list