c++ - Xcode写c语言的代码,如何用freopen()让输出回到控制台?
本文介绍了c++ - Xcode写c语言的代码,如何用freopen()让输出回到控制台?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
请问,我讲stdout定义到了文件之后,想要返回Xocde的控制台重新在console里输出第二个hello用什么语法可以回来?
freopen("/dev/tty/", "a", stdout);已经试过了但是没有反应。
在此之前已经搜过很多地方了,实在不知道该怎么解决了,第一次提问。多谢各位大佬了。?
解决方案
参考这篇文章
Once I've used freopen, how can I get the original stdout (or stdin) back?
如果需要还原stdout,其实不推荐使用freopen,推荐的做法是
使用一个文件指针FILE *ofp
把所有的printf( ... )
替换成fprintf(ofp, ... )
然后你可以把ofp指向文件、指向stdout、等等。
注意,尝试用文件指针去保存stdout,是错误的。因为通常stdout会包含无法再分配的内容。(stdin和stderr也同样)
FILE *savestdout = stdout;
stdout = fopen(file, "w"); /* WRONG */
stdout = savestdout; /* WRONG */
另一种解决方案,使用dup or dup2
(以下代码转载自http://c-faq.com/stdio/rd.kir...)
/*
* Sample code posted by Lawrence Kirby
* Date: Mon, 02 Mar 98 01:51:38 GMT
* Subject: temporarily reassigning stdout/stderr
* Message-ID: <28182@genesis.demon.co.uk>
*
* (Nonportable: uses dup() and dup2() system calls for
* duplicating underlying file descriptors, which are
* present in Unix but not necessarily anywhere else.)
*/
#include <stdio.h>
main()
{
int fd;
fpos_t pos;
printf("stdout, ");
fflush(stdout);
fgetpos(stdout, &pos);
fd = dup(fileno(stdout));
freopen("stdout.out", "w", stdout);
f();
fflush(stdout);
dup2(fd, fileno(stdout));
close(fd);
clearerr(stdout);
fsetpos(stdout, &pos); /* for C9X */
printf("stdout again\n");
}
f()
{
printf("stdout in f()");
}
这篇关于c++ - Xcode写c语言的代码,如何用freopen()让输出回到控制台?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文