How to redirect printf() to file and then back to console

后端 未结 2 1493
走了就别回头了
走了就别回头了 2021-01-16 18:54

I am working on a project that requires me to have output from within a mini shell on my C program to output to a file. Using ./program > file.txt wi

2条回答
  •  再見小時候
    2021-01-16 19:39

    You can use freopen.

    freopen("desiredFileName", "w", stdout);
    

    Once you are done, you can undo the reassignment like this:

    freopen("/dev/stdout", "w", stdout);
    

    on Unix/Linux systems. I'm not sure whether there is a portable way to revert back.

    UPDATE

    If possible, you can use fprintf instead of printf, providing either stdout or a handle to the desired file, as appropriate.

提交回复
热议问题