流和llvm错误

时间:2011-10-16 14:39:33

标签: c visual-studio stream llvm

这是函数的代码:

int getStream()
    {
           int fd = _dup(fileno(stdout));
           freopen("tmp","w",stdout);
           return fd;
    }


void freeStream(int fd)
{
       _dup2(fd,fileno(stdout));
       close(fd);
}

主程序代码:

printf(“start tets”);
int fd = getStream();
printf(“redirection”);
freeStream(fd);

这是使用llvm的大型程序的一部分 我在freeStream(fd)之后遇到的问题:LLVM ERROR: IO failure on output stream. 我知道问题出在freeStream实现上。 你怎么看? 感谢

2 个答案:

答案 0 :(得分:3)

如果要在临时文件中可靠地看到文本"redirection"结束,则需要在关闭缓冲区之前清除stdout中的缓冲区以清除任何挂起的写入缓冲在流中。要完成此操作,请将此行添加到freeStream函数:

void freeStream(int fd)
{
   fflush(stdout); //<== add this line
   _dup2(fd,fileno(stdout));
   close(fd);
}

答案 1 :(得分:2)

正如Jason诊断的那样,在关闭基础文件之前(通过fflush()调用),您需要stdout流(_dup2())。

另一个问题是代码中没有错误检查;你不知道你的函数调用哪个(如果有的话)失败了。至少在解决此问题时,您需要同时监控freopen()_dup2()以确保它们有效。

目前尚不清楚在Windows上,您可以到达<stdio.h>库的后面并更改文件描述符。在Unix上,我认为它可能会起作用 - 不一定支持,但可能会起作用。但我很容易想象它在Windows上失败的方式(不确定我的想象力不仅仅是生动)。

最终,我不相信在使用stdout之后有一种可移植的方法可以将freopen()恢复为原始输出。