Skip to content

Commit 5f2b456

Browse files
committed
methods for print()
1 parent 9aa9bb1 commit 5f2b456

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

src/file_manager.cpp

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,4 +53,37 @@ void FileManerger::setFileName(const std::string& value) {
5353
std::unique_lock<std::shared_mutex> lock(mutex_);
5454
file_name_ = value;
5555
}
56+
57+
void FileManerger::captureStdout(std::function<void()> func) {
58+
std::unique_lock<std::shared_mutex> lock(mutex_);
59+
60+
if (!file_stream_.is_open()) {
61+
throw std::runtime_error(
62+
"File stream is not open. Call createFile() first.");
63+
}
64+
65+
// 保存原来的 cout buffer
66+
std::streambuf* old_cout_buf = std::cout.rdbuf();
67+
68+
// 创建一个 stringstream 来捕获输出
69+
std::stringstream captured_output;
70+
71+
// 重定向 cout 到 stringstream
72+
std::cout.rdbuf(captured_output.rdbuf());
73+
74+
try {
75+
// 执行函数
76+
func();
77+
78+
// 恢复 cout
79+
std::cout.rdbuf(old_cout_buf);
80+
81+
// 将捕获的输出写入文件
82+
file_stream_ << captured_output.str();
83+
} catch (...) {
84+
// 确保恢复 cout
85+
std::cout.rdbuf(old_cout_buf);
86+
throw;
87+
}
88+
}
5689
} // namespace paddle_api_test

src/file_manager.h

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
#pragma once
22
#include <fstream>
3+
#include <functional>
34
#include <mutex>
45
#include <shared_mutex>
56
#include <string>
@@ -16,6 +17,9 @@ class FileManerger {
1617
FileManerger& operator<<(const std::string& str);
1718
void saveFile();
1819

20+
// 捕获标准输出到文件
21+
void captureStdout(std::function<void()> func);
22+
1923
private:
2024
mutable std::shared_mutex mutex_;
2125
std::string basic_path_ = "/tmp/paddle_cpp_api_test/";

0 commit comments

Comments
 (0)