在程序执行期间从标准输出重定向到自定义流

问题描述 投票:0回答:1

我有一个功能,可将消息从标准输出重定向到日志文件。问题是,仅在程序结束后才将消息写入日志文件。程序运行时是否可以写入日志文件?因此,在每个std::cout之后,将新行添加到日志文件。我应该进行哪些更改?

struct Node{
        char data[100];
        struct Node* next;
    };

    class capturebuf : public std::stringbuf{
    public:
        capturebuf(){
            head = NULL;
            filename = "D:/checkouts/pointcloudbuilder/scene_plugin/log.txt";
            log.open(filename);
        }
    protected:
        struct Node* head;
        std::string filename;
        std::ofstream log;

        virtual int sync(){
                //ensure NUL termination
                overflow(0);

                struct Node* new_node = new Node();
                strcpy(new_node->data, pbase());
                new_node->next = head;
                head = new_node;

                log << head->data;

                //clear buffer
                str(std::string());
                return __super::sync();
        }
    };
    struct scoped_cout_streambuf_association{
        std::streambuf* orig;
        scoped_cout_streambuf_association( std::streambuf& buf )
            : orig(std::cout.rdbuf()){
                std::cout.rdbuf(&buf);
            }
            ~scoped_cout_streambuf_association(){
                std::cout.rdbuf(orig);
            }
    };

在]中>

int main() {
    capturebuf altout;
    scoped_cout_streambuf_association redirect(altout);
    return 0;
}

我有一个功能,可将消息从标准输出重定向到日志文件。问题是,仅在程序结束后才将消息写入日志文件。是否可以写...

c++ stringstream c++-standard-library streambuf ostringstream
1个回答
2
投票

流已缓冲,因此您需要使用std::flush显式刷新流。此question中的更多信息。

© www.soinside.com 2019 - 2024. All rights reserved.