So, I fiddled around a little. First things first: I found dup and dup2 in the 
MingW sources. Is this why it is working out of the box when compiling from 
MacOS to Windows? Anyways, your solution - with importing the dups - does the 
thing for windows, too :)

Consider the lovely phrase from the [Nim docs about 
getFileHandle](https://nim-lang.org/docs/io.html#getFileHandle):

> Note that on Windows this doesn't return the Windows-specific handle, but the 
> C library's notion of a handle, whatever that means.

I can just "target" Nim's FileHandle from stdout.getFileHandle() all the time 
(refer to example code).
    
    
    const tempStdoutFileName = "stdout_temp.txt"
    
    proc dup(oldfd: FileHandle): FileHandle {.importc, header: "unistd.h".}
    proc dup2(oldfd: FileHandle, newfd: FileHandle): cint {.importc, header: 
"unistd.h".}
    
    echo "before..."
    
    let caught = open(tempStdoutFileName, fmWrite)
    let oldStdoutHandle = dup(stdout.getFileHandle())
    discard dup2(caught.getFileHandle(), stdout.getFileHandle())
    
    #body
    echo "Run, Forest, run!"
    
    caught.flushFile()
    discard dup2(oldStdoutHandle, stdout.getFileHandle())
    caught.close()
    
    echo "...after"
    
    echo readFile(tempStdoutFileName)
    
    
    Run

And a good read (at least for me while trying to understand): [SO explanation 
of file 
descriptors](https://stackoverflow.com/questions/33536061/file-descriptors-and-file-handles-and-c)
 and [SO explanation of 
dup](https://stackoverflow.com/questions/7861611/can-someone-explain-what-dup-in-c-does).
 ( No aversion, here :D )

Reply via email to