在程序执行期间从标准输出重定向到自定义流
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 显式刷新流。此问题中的详细信息。
更改此函数应该会有所帮助:
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();
}
相关文章:
- 如何将stdout重定向到stderr
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 如何将点击的信号和插槽添加到qt中的自定义按钮中
- C++自定义比较函数
- 如何比较自定义类的std::变体
- std::设置自定义比较器
- 如何正确实现和访问运算符的各种自定义枚举器
- flutter:即使shouldRepaint()返回true,自定义画家也不会重新绘制
- 自定义先决条件对移动分配运算符有效吗
- 使用VS Code和CMake Tools运行自定义命令
- 如何创建从Maya(或类似程序)到虚幻引擎的自定义数据导出插件
- 编写时C++中的输入重定向问题
- std::ranges::elements_view,用于自定义类似元组的数据
- 跟随整数索引列表的自定义类迭代器
- 参数化自定义CMake工具链
- 使用自定义比较函数使用std::sort()对矢量字符串进行排序时出现问题
- C++ WinAPI[GDI].自定义 gui 正确重绘
- 在程序执行期间从标准输出重定向到自定义流
- 自定义 QGraphicItem 和重绘问题
- 将syslog设施日志重定向到自定义文件