Here is the code of the functions:
int getStream()
{
int fd = _dup(fileno(stdout));
freopen("tmp","w",stdout);
return fd;
}
void freeStream(int fd)
{
_dup2(fd,fileno(stdout));
close(fd);
}
The code of main program:
printf(“start tets”);
int fd = getStream();
printf(“redirection”);
freeStream(fd);
This is a part of large program which uses llvm
The problem I get after freeStream(fd): LLVM ERROR: IO failure on output stream.
I understand that the problem is with freeStream implementation.
What do you think?
Thanks
As Jason diagnosed, you need to
fflush()the stream (stdout) before you close the underlying file (via the_dup2()call).Another problem is that there is no error checking in the code; you don’t know which, if any, of your function calls are failing. At least while resolving this issue, you need to monitor both
freopen()and_dup2()to ensure they work.It is not clear that on Windows, you can reach behind the back of the
<stdio.h>library and change the file descriptor. On Unix, I think it would likely work – not necessarily supported, but probably it would work. But I can easily imagine ways it fails on Windows (without being certain that my imagination is not simply being to vivid).Ultimately, I am not convinced there’s a portable way to reinstate
stdoutback to its original output after usingfreopen()on it.