freopen:恢复到原始流
我需要将标准输出转发到不同的文件,以分离生成的一些打印并恢复到正常的标准输出。
我使用 freopen 以这种方式切换到文件:
char name[80];
memset(name, 0, 80);
strcpy(name, "./scripts/asm/");
strcat(name, m_func->m_name->m_value);
strcat(name, ".shasm");
freopen(name, "w", stdout);
它实际上有效,但在过程结束时(请注意 stdout 以之前相同的方式重定向了很多次)我无法将其恢复为原始标准输出。我尝试了以下操作:
freopen("/dev/stdout", "w", stdout);
但它似乎不起作用..只是为了我在 macOS 上开发的信息。
我应该怎么办?
提前致谢
I needed to forward stdout to different files to separate some prints produced and the reverting back to normal stdout.
I used freopen
to switch to the file in this way:
char name[80];
memset(name, 0, 80);
strcpy(name, "./scripts/asm/");
strcat(name, m_func->m_name->m_value);
strcat(name, ".shasm");
freopen(name, "w", stdout);
And it actually works, but at the end of the process (mind that stdout is redirected many times in the previous same way) I'm not able to revert it to original stdout. I tried the following:
freopen("/dev/stdout", "w", stdout);
but it doesn't seem to work.. just for information I'm developing on macosx.
What should I do?
Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这可以使用 fileno、dup 和 dup2 调用来实现。我已经在 Linux 上尝试过了,不确定这是否适用于 Mac,但我相信您会为您的设置获得一些等效的功能。看看这个示例代码是否适合您。抱歉,代码中缺少错误处理。 :)
This can be achieved using fileno, dup and dup2 calls. I have tried this on linux not sure whether this will work on mac but I am sure you will get some equivalent functions for your setup. See if this sample code works for you. Sorry for lack of error-handling in the code. :)
这似乎是解决问题的一种迂回方式。为什么不直接使用
fopen()
打开每个文件,然后使用fputs
、fprintf
写入其FILE *
,fwrite
等?无需重定向标准输出。This seems like a roundabout way of solving your problem. Why not just open each file with
fopen()
and then writing to itsFILE *
withfputs
,fprintf
,fwrite
etc? No need to redirect stdout.