redirect std out to a string?
wolframw
wolframw at protonmail.com
Thu May 21 21:47:38 UTC 2020
On Thursday, 21 May 2020 at 15:42:50 UTC, Basile B. wrote:
> On Thursday, 21 May 2020 at 04:29:30 UTC, Kaitlyn Emmons wrote:
>> is there a way to redirect std out to a string or a buffer
>> without using a temp file?
>
> yes:
>
> [snip]
Alternatively, setvbuf can be used:
void[1024] buf; // buffer must be valid as long as the program
is running [1]
// (buffer could also be heap-allocated; see
Basile's post)
void main()
{
import std.stdio;
import std.string : fromStringz;
stdout.reopen("/dev/null", "a"); // on Windows, "NUL" should
do the trick
stdout.setvbuf(buf);
writeln("Hello world", 12345);
stdout.writeln("Hello again");
// Lastly, fromStringz is used to get a correctly sized
char[] from the buffer
char[] mystr = fromStringz(cast(char *) buf.ptr);
stderr.writeln("Buffer contents:\n", mystr);
}
[1] https://en.cppreference.com/w/c/io/setvbuf#Notes
More information about the Digitalmars-d-learn
mailing list