Tcl C API: redirect stdout of embedded Tcl interp to a file without affecting the whole program

前端 未结 3 428
终归单人心
终归单人心 2021-01-26 00:07
#include 
int main(int argc, char** argv)
{
    Tcl_Interp *interp = Tcl_CreateInterp();

    Tcl_Channel stdoutChannel = Tcl_GetChannel(interp, \"stdout\",         


        
3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-26 00:30

    At the level of the C API, and assuming that you are on a Unix-based OS (i.e., not Windows), you can do this far more simply by using the right OS calls:

    #include 
    #include 
    
    // ... now inside a function
    
        int fd = open("/home/aminasya/nlb_rundir/imfile", O_WRONLY|O_CREAT, 0744);
        // Important: deal with errors here!
    
        dup2(fd, STDOUT_FILENO);
        close(fd);
    

    You could also use dup() to save the old stdout (to an arbitrary number that Tcl will just ignore) so that you can restore it later, if desired.

提交回复
热议问题