如果要将重定向了的标准流恢复到初始状态,可以使用标准C库函数dup()和fdopen()。
dup()函数可以复制一个文件句柄,你可以用dup()函数保存对应于stdout标准流的文件句柄。fdopen()函数可以打开一个已用dup()函数复制了的流。这样,你就可以重定向并恢复标准流,请看下例:
- #include <stdio.h>
- void main(void);
- void main(void)
- {
- int orig-stdout;
- /* Duplicate the stdout file handle and store it in orig_stdout. */
- orig_stdout = dup (fileno (stdout));
- /* This text appears on-screen. */
- printf("Writing to original stdout... \n") ;
- /* Reopen stdout and redirect it to the "redir. txt" file. */
- freopen("redir.txt", "w", stdout);
- /* This text appears in the "redir. txt" file. */
- printf("Writing to redirected stdout.., \n");
- /* Close the redirected stdout. */
- fclose (stdout);
- /* Restore the original stdout and print to the screen again. */
- fdopen(orig_stdout, "w" );
- printf("I'm back writing to the original stdout. \n");
- }