我有一个将消息从标准输出重定向到日志文件的函数。问题是,消息仅在程序结束后写入日志文件。程序运行时是否可以写入日志文件?因此,在每次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 显式刷新流。此问题中的详细信息。
更改此函数应该会有所帮助:
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();
}