强制打印到终端(std :: cout正在管道)

时间:2017-07-31 23:23:58

标签: c++ io std cout

上下文

我正在编辑一个大型程序的一小部分。这个大程序控制std :: cout并重新路由它,以便像:

这样的基本代码
std::cout << "I want to see the light of the terminal!" << std::endl;

不向用户显示任何内容。

问题:

当我的标准输出/错误被重新路由时,如何才能将直接直接打印到终端? (如果可能的话)

其他说明:

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

我目前也正在写一个文件作为一种解决方法,但这有点不太可取,坦率地说,我想知道将来如何做到这一点。

2 个答案:

答案 0 :(得分:2)

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

  1. 保存重定向缓冲区

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

  3. 完成工作

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

  5. 例如

    #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获取了这个想法和例子。

    为方便起见,您只需编写一个在控制台中打印的功能即可。此功能将负责重定向和打印。

答案 1 :(得分:0)

写入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;
}