我有一个功能,可将消息从标准输出重定向到日志文件。问题是,仅在程序结束后才将消息写入日志文件。程序运行时是否可以写入日志文件?因此,在每个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显式刷新流。此question中的更多信息。