我想将两个(或更多)流组合成一个.我的目标是将任何输出定向到cout,cerr并且clog还将其与原始流一起输出到文件中.(例如,当事情记录到控制台时.关闭后,我仍然希望能够返回并查看输出.)
我在考虑做这样的事情:
class stream_compose : public streambuf, private boost::noncopyable
{
public:
// take two streams, save them in stream_holder,
// this set their buffers to `this`.
stream_compose;
// implement the streambuf interface, routing to both
// ...
private:
// saves the streambuf of an ios class,
// upon destruction restores it, provides
// accessor to saved stream
class stream_holder;
stream_holder mStreamA;
stream_holder mStreamB;
};
Run Code Online (Sandbox Code Playgroud)
这看起来很简单.然后在main中的调用将是这样的:
// anything that goes to cout goes to both …Run Code Online (Sandbox Code Playgroud) 我读了这个主题,但他的问题可能与我写入stdout和文件有所不同
我想写一个函数,该函数需要打印到stdout和一个文件.我的C程序通过scanf获取用户输入.
我打算写一个像printf这样的函数,但我真的不知道如何:
我试过这个,但它只能用"纯"字符串,不能转换%d,%.*lf(我的打印功能只需要两次转换)
void dupPrint(FILE *fp,char *string)
{
printf("%s",string);
fprintf(fp,"%s",string);
return;
}
Run Code Online (Sandbox Code Playgroud)
我试过dup2和freopen,但它们对我不起作用.
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
int main()
{
int i;
int file = open("input3.txt", O_APPEND | O_WRONLY);
if(file < 0) return 1;
if(dup2(file,1) < 0) return 1;
printf("Redirect to file!\n");
printf("enter i : ");
scanf("%d",&i);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这个dup2()教程只打印到文件.
我也试过tee,但可能不行,因为我必须得到用户的输入(如果工作,那不是"公平的"因为tee不在我的程序中).
我认为实现类似printf会解决问题,但我不知道如何转换.*lf(用户输入精度打印输出double)
#include <stdio.h>
#include <stdarg.h>
void dupPrint(FILE *fp,char *fmt, ...)
{
va_list ap;
char *p, *sval;
int ival;
double dval;
va_start (ap, fmt); …Run Code Online (Sandbox Code Playgroud) 我正在制作的程序旨在无人值守运行,因此我将stdout和stderr流重定向到日志文件.虽然这没有任何问题,但我仍在制作和调试软件,我希望它也显示在屏幕上.这可能吗?
重定向我使用过的流
System.setErr(logWriter);
System.setOut(logWriter);
Run Code Online (Sandbox Code Playgroud)
谢谢.