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

Redirecting from standard output to custom stream during program execution

我有一个函数可以将消息从标准输出重定向到日志文件。问题是,消息只在程序结束后写入日志文件。程序是运行时是否可以写入日志文件?因此,在每个 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;
}

流被缓冲,因此您需要使用 std::flush. More info in this question.

显式刷新您的流

更改此功能应该有所帮助:

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 << std::flush; // << add explicit flush

        //clear buffer
        str(std::string());
        return __super::sync();
}