llvm and stream error

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

Yakov