Rerouting stdin and stdout from C

前端 未结 8 1387
终归单人心
终归单人心 2020-11-22 12:15

I want to reopen the stdin and stdout (and perhaps stderr while I\'m at it) filehandles, so that future calls to printf()

相关标签:
8条回答
  • 2020-11-22 12:56

    The os function dup2() should provide what you need (if not references to exactly what you need).

    More specifically, you can dup2() the stdin file descriptor to another file descriptor, do other stuff with stdin, and then copy it back when you want.

    The dup() function duplicates an open file descriptor. Specifically, it provides an alternate interface to the service provided by the fcntl() function using the F_DUPFD constant command value, with 0 for its third argument. The duplicated file descriptor shares any locks with the original.

    On success, dup() returns a new file descriptor that has the following in common with the original:

    • Same open file (or pipe)
    • Same file pointer (both file descriptors share one file pointer)
    • Same access mode (read, write, or read/write)
    0 讨论(0)
  • 2020-11-22 13:04

    freopen solves the easy part. Keeping old stdin around is not hard if you haven't read anything and if you're willing to use POSIX system calls like dup or dup2. If you're started to read from it, all bets are off.

    Maybe you can tell us the context in which this problem occurs?

    I'd encourage you to stick to situations where you're willing to abandon old stdin and stdout and can therefore use freopen.

    0 讨论(0)
提交回复
热议问题