我将我的标准输出数据重定向到std::ofstream缓冲区,以便将数据写入文件。以下代码实现了这一点,
if ( isActive ){
try{
std::string traceFileName = "traceLog"+getTime()+".log";
std::ofstream out(traceFileName.c_str());
std::streambuf *countbuf = std::cout.rdbuf();
std::cout.rdbuf ( out.rdbuf() ) ;
std::cout<<"buffer pointed\n"<<std::endl;
}当我在单个.cpp中实现上面的代码时,在下面的场景中,它将被执行,而数据将在file.But中写入。
A( bool isActive){
if ( isActive ){
try{
std::string traceFileName = "traceLog"+getTime()+".log";
std::ofstream out(traceFileName.c_str());
std::streambuf *countbuf = std::cout.rdbuf();
std::cout.rdbuf ( out.rdbuf() ) ;
std::cout<<"buffer pointed\n"<<std::endl;
}从不同的.cpp调用函数A( true ),我希望在调用A()之后,在我的整个c++项目中,当“打印数据\n”时,数据将被打印到文件中。但是我的代码编译得很好,在运行时抛出了以下错误,
(process:10365): GConf-WARNING **: Client failed to connect to the D-BUS daemon:未收到回复。可能的原因包括:远程应用程序没有发送回复、消息总线安全策略阻止了回复、回复超时或网络连接中断。
(进程:10365):GConf-WARNING **:客户端无法连接到D-BUS守护进程:未收到回复。可能的原因包括:远程应用程序没有发送回复、消息总线安全策略阻止了回复、回复超时或网络连接中断。
(进程:10365):GConf-WARNING **:客户端无法连接到D-BUS守护进程:未收到回复。可能的原因包括:远程应用程序没有发送回复、消息总线安全策略阻止了回复、回复超时或网络连接中断。QGtkStyle无法检测当前的GTK+主题。Qt:会话管理错误:不支持指定的任何身份验证协议
但是如果我把下面的代码放在main中,
std::string traceFileName = "traceLog"+getTime()+".log";
std::ofstream out(traceFileName.c_str());
std::streambuf *countbuf = std::cout.rdbuf();
std::cout.rdbuf ( out.rdbuf() ) ;运行时所有std::cout数据都将写入文件中。ut抛出以下错误。我该如何解决这个错误。
enter code here(process:10777): GConf-WARNING **: Client failed to connect to the D-BUS daemon:未收到回复。可能的原因包括:远程应用程序没有发送回复、消息总线安全策略阻止了回复、回复超时或网络连接中断。
(进程:10777):GConf-WARNING **:客户端无法连接到D-BUS守护进程:未收到回复。可能的原因包括:远程应用程序没有发送回复、消息总线安全策略阻止了回复、回复超时或网络连接中断。
(进程:10777):GConf-WARNING **:客户端无法连接到D-BUS守护进程:未收到回复。可能的原因包括:远程应用程序没有发送回复、消息总线安全策略阻止了回复、回复超时或网络连接中断。QGtkStyle无法检测当前的GTK+主题。Qt:会话管理错误:不支持指定的任何身份验证协议
发布于 2014-03-02 22:08:47
问题是,在离开创建文件流的作用域之前,没有恢复缓冲区。std::cout仍将持有指向它最终尝试写入的缓冲区的指针。
我认为一种选择是让out static,另一种是创建一个类,在作用域剩余时将原始缓冲区重新分配给std::cout:
class buffer_restore
{
public:
buffer_restore(std::ios& _ios)
: ios(_ios)
, sbuf(_ios.rdbuf())
{ }
~buffer_restore()
{
ios.rdbuf(sbuf);
}
private:
std::ios& ios;
std::streambuf* sbuf;
};下面是一个如何使用它的示例:
{
buffer_restore br(std::cout);
std::ofstream out(traceFileName.c_str());
std::streambuf* countbuf = std::cout.rdbuf(out.rdbuf());
} // std::cout's buffer is restored to the original when br was constructedhttps://stackoverflow.com/questions/22124689
复制相似问题