redirect std out to a string?

Basile B. b2.temp at gmx.com
Thu May 21 15:42:50 UTC 2020


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().


More information about the Digitalmars-d-learn mailing list