强制打印到终端(正在传输 std::cout)

Force print to terminal (std::cout is being piped)

上下文:

我正在编辑一个大程序的一小部分。这个大型程序正在控制 std::cout 并重新路由它,这样一段基本代码如:

std::cout << "I want to see the light of the terminal!" << std::endl;

不向用户显示任何内容。

问题:

当我的标准 output/error 被重新路由时,我怎样才能让直接 打印到终端? (如果可能的话)

其他说明:

我知道我可以编辑更大的程序,但我希望在将我的代码更完全地集成到程序中之前使用此打印输出进行一些早期诊断。必须弄乱程序如何路由输出会真正延长开发周期。

我目前也在写入一个文件作为解决方法,但这不太令人满意,坦率地说,我想知道将来如何做到这一点。

我认为您可以按照以下步骤进行操作:

  1. 保存重定向缓冲区

  2. 将缓冲区更改为控制台

  3. 完成你的工作

  4. 再次将缓冲区设置为步骤1中保存的缓冲区

例如

#include <sstream>
#include <iostream>

void print_to_console() {
    std::cout << "Hello from print_to_console()" << std::endl;
}

void foo(){
  std::cout<<"hello world"<<std::endl; 
  print_to_console(); // this could be printed from anything
}
int main()
{
    std::stringstream ss;

    //change the underlying buffer and save the old buffer
    auto old_buf = std::cout.rdbuf(ss.rdbuf()); 

    foo(); //all the std::cout goes to ss

    std::cout.rdbuf(old_buf); //reset

    std::cout << "<redirected-output>\n" 
              << ss.str() 
              << "</redirected-output>" << std::endl;
}

我还没有测试过。我从 this accepted answer.

中获取了想法和示例

为了方便,你可以写一个函数在控制台打印。此函数将负责重定向和打印。

写入 stdout 并从 stdin 读取(都是 FILE 描述符)。 如果您愿意,可以将它们包装在流 类 中。IE:使用 streambufiostream 获得与 cout.

相同的功能
#include <iostream>



int main(int argc, const char * argv[]) {

    const char* data = "DATA TO PRINT";
    fwrite(data, strlen(data), sizeof(char), stdout);

    return 0;
}

小例子:

#include <iostream>

class stream : public std::streambuf
{
private:
    int_type overflow(int_type c  = traits_type::eof());

public:
    stream() {}
    virtual ~stream() {}

    stream(const stream& other) = delete;
    stream& operator = (const stream& other) = delete;
};

stream::int_type stream::overflow(stream::int_type c)
{
    if (c != traits_type::eof())
    {
        fwrite(&c, 1, sizeof(c), stdout);
    }

    return c;
}

class mcout : public std::ostream
{
public:
    mcout() : std::ostream(0), sbuf() {init(&sbuf);}
    virtual ~mcout() {}

private:
    stream sbuf;
} mcout;

int main(int argc, const char * argv[]) {

    mcout << "HELLO\n";

    return 0;
}