簡體   English   中英

強制打印到終端(正在對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;

不向用戶顯示任何內容。

題:

重新路由我的標准輸出/錯誤時,如何才能將某些內容直接打印到終端上? (如果可能的話)

其他說明:

我意識到我可以編輯更大的程序,但是在將代碼更完全地集成到程序中之前,我希望將此打印輸出用於一些早期診斷。 不得不弄亂程序如何路由輸出將真正延長開發周期。

目前,我也正在將文件寫為解決方法,但這不太理想,坦率地說,我想知道將來如何做。

我認為您可以按照以下步驟進行操作:

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

我還沒有測試。 我從這個公認的答案中得到了想法和例子。

為了方便起見 ,您可以編寫一個要在控制台中打印的功能。 此功能將負責重定向和打印。

寫到stdout和讀取stdin (均為FILE描述符)。 如果願意,可以將它們包裝在流類中streambuf :使用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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM