Thread overview
redirect std out to a string?
May 21
Dukc
May 21
Basile B.
May 21
wolframw
May 21
is there a way to redirect std out to a string or a buffer without using a temp file?
May 21
On 5/21/20 12:29 AM, Kaitlyn Emmons wrote:
> is there a way to redirect std out to a string or a buffer without using a temp file?

D's I/O is dependent on C's FILE * API, so if you can make that write to a string, then you could do it in D.

I don't think there's a way to do it in C. So likely the answer is no.

-Steve
May 21
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?

If you want to do the redirection at startup, it's possible. Have an another program to start your program by std.process functions and redirect stdout to a pipe. The outer program can then handle the output of the inner program however it wishes. Clumsy but possible.

But I don't know whether a process can redirect it's own standard input or output.
May 21
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:

---
#!dmd -betterC
module runnable;

extern(C) int main()
{
    import core.sys.posix.stdio : fclose, stdout, fmemopen, printf, fflush;
    import core.stdc.stdlib : malloc;

    char* buff;
    enum s = "this will use a buffer from the heap that has, " ~
             "just like a file, a FD thanks to fmemopen()";

    fclose(stdout);
    buff = cast(char*) malloc(4096);
    buff[0..4096] = '\0';
    stdout = fmemopen(buff, 4096, "wr+");
    printf(s);
    fflush(stdout);
    assert(buff[0..s.length] == s);
    return 0;
}
---

something similar should be possible using mmap().
May 21
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