Skip to content

Commit 556a527

Browse files
committed
methods for print()
1 parent bfd2a2f commit 556a527

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
@@ -70,4 +70,37 @@ void FileManerger::setFileName(const std::string& value) {
7070
std::unique_lock<std::shared_mutex> lock(mutex_);
7171
file_name_ = value;
7272
}
73+
74+
void FileManerger::captureStdout(std::function<void()> func) {
75+
std::unique_lock<std::shared_mutex> lock(mutex_);
76+
77+
if (!file_stream_.is_open()) {
78+
throw std::runtime_error(
79+
"File stream is not open. Call createFile() first.");
80+
}
81+
82+
// 保存原来的 cout buffer
83+
std::streambuf* old_cout_buf = std::cout.rdbuf();
84+
85+
// 创建一个 stringstream 来捕获输出
86+
std::stringstream captured_output;
87+
88+
// 重定向 cout 到 stringstream
89+
std::cout.rdbuf(captured_output.rdbuf());
90+
91+
try {
92+
// 执行函数
93+
func();
94+
95+
// 恢复 cout
96+
std::cout.rdbuf(old_cout_buf);
97+
98+
// 将捕获的输出写入文件
99+
file_stream_ << captured_output.str();
100+
} catch (...) {
101+
// 确保恢复 cout
102+
std::cout.rdbuf(old_cout_buf);
103+
throw;
104+
}
105+
}
73106
} // 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>
@@ -17,6 +18,9 @@ class FileManerger {
1718
FileManerger& operator<<(const std::string& str);
1819
void saveFile();
1920

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

0 commit comments

Comments
 (0)