IO 模块详解
IO 类负责用于测试数据生成时的输入/输出便捷操作。它提供文件写入、原子写、读取、以及将任意流绑定到文件的轻量机制。
主要成员简介
- 构造器:
IO(const std::string& input_name, const std::string& output_name = "") input_name:输入文件路径(可为空)。-
output_name:输出文件路径(可为空)。 -
read_output_all()->std::string -
读取
output_filename指向的文件全部内容为字符串(若文件存在)。 -
write_atomic(filename, data) - 将数据写入临时文件后重命名为目标文件,尽量保证写入为原子操作。
-
注意:跨文件系统或不支持原子重命名的环境可能不会保证完全的原子性。
-
writeline(line) -
追加一行并换行(便捷写法,依赖
output_file已打开)。 -
bind_input_stream(std::istream&)/bind_output_stream(std::ostream&) -
将任意流与文件交互,便于在测试中使用
std::stringstream或捕获输出到自定义流。 -
createof(executable_path)(已有实现) - 用
system()调用可执行文件,以input_filename做标准输入并将标准输出重定向到output_filename。 - 注意:该方法使用
std::system,在跨平台或安全敏感场景下应谨慎使用(存在 shell 注入风险)。
使用示例
using namespace STAR_CPP;
IO io("in.txt", "out.txt");
io.writeline("1 2 3 4");
// 原子写:
io.write_atomic("config.json", "{\"k\":1}\n");
// 读取输出:
auto text = io.read_output_all();
std::cout << text;
// 绑定 stringstream 流
std::istringstream sin("5 6 7");
io.bind_input_stream(sin);
std::ostringstream sout;
io.bind_output_stream(sout);
最佳实践与注意点
- 在并发写入场景下尽量使用
write_atomic,但仍需确保两次写入不在不同文件系统。 bind_input_stream实现为“将流内容写入文件”的轻量适配;如果需要直接在内存中操作,请使用std::stringstream与Random/Sequence的返回值直接组合。- 若需要更安全的外部程序执行(替代
createof),可使用平台特定的进程 API(CreateProcess/posix_spawn/fork+exec)并传参避免 shell。