After redirecting standard input and output to some files(for example) using freopen how can I redirect them back to where they were at the very beginning?
After redirecting standard input and output to some files(for example) using freopen how can
Share
You can duplicate/clone the initial FD’s using
id = fcntl(blah,F_DUPFD,0), and then usedup2(0,id)to copy it back (after closing stdin!), then reopen the file using fdopen(). Repeat for the others. However, that probably doesn’t get you what you want exactly – it gets you a random filehandle that is associated with FD 0, not changing ‘stdin’.Another kind-of ugly option is to spawn off a thread (which implicitly dups stdin/etc), fdreopen them, do your processing, then exit the thread (closing the reopened stdin/etc) and unblock the main process (which never was changed). This is indirect but probably both portable and guaranteed to work.