第11.19章: 临时文件
概述
临时文件用于存放只需短暂存在的数据。fast_io 提供 ::fast_io::io_temp 来创建关闭时自动删除的临时文件。
创建临时文件
要创建临时文件,把 ::fast_io::io_temp 传给任何文件类型的构造函数。文件被创建在系统的临时目录里(例如 Unix 上的 /tmp,Windows 上的 %TEMP%)。当文件对象离开作用域时,文件被自动关闭并删除。
#include <fast_io.h>
#include <fast_io_device.h>
int main() {
using namespace ::fast_io::iomnp;
// Create a temporary file with obuf_file
::fast_io::obuf_file obf(::fast_io::io_temp);
// Write to it like any other file
println(obf, "Temporary data: ", 42);
println(obf, "More data: ", 3.14159);
// File is automatically deleted when `obf` goes out of scope
}
::fast_io::io_temp 可用于任何文件类型:
#include <fast_io.h>
#include <fast_io_device.h>
int main() {
using namespace ::fast_io::iomnp;
// Temporary file with C stdio interface
::fast_io::c_file cf(::fast_io::io_temp);
fprintf(cf.fp, "Temporary data\n");
// Temporary buffered file
::fast_io::obuf_file obf(::fast_io::io_temp);
println(obf, "Buffered temporary data");
// Temporary input/output file
::fast_io::iobuf_file iof(::fast_io::io_temp);
println(iof, "Read-write temporary data");
// All files are deleted automatically when they go out of scope
}
重要:临时文件只在文件对象存活期间存在。一旦它离开作用域,文件就被关闭并从文件系统中删除。这就是 RAII — 你永远不会忘记清理临时文件。
从临时文件读取
你也可以从临时文件读。由于临时文件是以读写权限打开的,你可以写入数据、定位回开头,然后读出来:
#include <fast_io.h>
#include <fast_io_device.h>
int main() {
using namespace ::fast_io::iomnp;
// Create a temporary file (read-write)
::fast_io::native_file temp(::fast_io::io_temp);
// Write data
println(temp, "Line 1");
println(temp, "Line 2");
println(temp, "Line 3");
// Seek back to beginning
::fast_io::rewind(temp);
// Read it back
for (::fast_io::string line; scan<true>(temp, str_line_get(line)); ) {
println("Read: ", line);
}
// File is deleted automatically when temp goes out of scope
}
临时文件与普通文件的区别
为什么要用 io_temp,而不是直接打开一个普通文件?
- 自动清理:对象离开作用域时文件被删除,即使抛出了异常也是如此。
- 安全的位置:文件被创建在系统的临时目录里,那正是临时数据该在的地方。
- 不会重名:系统会生成唯一的名字,所以你不必操心挑选文件名。
- 安全性:在某些系统上,临时文件以受限的权限创建。
与此对比,C 标准库的 tmpfile() 也会创建临时文件,但返回一个你必须手动关闭的 FILE*:
#include <stdio.h>
int main() {
FILE *tmp = tmpfile();
if (tmp == NULL) {
perror("tmpfile failed");
return 1;
}
fprintf(tmp, "Temporary data\n");
fclose(tmp); // File is deleted here
return 0;
}
用 fast_io 的 io_temp,你得到的是 RAII 语义 — 文件被自动清理,你永远不会忘记调用 fclose。
什么时候该用临时文件
临时文件适用于:
- 中间结果:处理大数据集时,你可以把中间结果写入临时文件,而不是全部留在内存里。
- 缓存:缓存那些重新计算代价很高的结果。
- 进程间通信:写入另一个进程要读的数据(尽管管道或共享内存往往更好)。
- 测试:为单元测试创建临时文件,而不污染文件系统。
要点
-
::fast_io::io_temp是传给文件构造函数的标签,用于在系统临时目录中创建临时文件。 -
文件对象离开作用域时,临时文件被自动删除。Linux 上使用
O_TMPFILE;Windows 上使用FILE_FLAG_DELETE_ON_CLOSE。 -
对只需短暂存在的数据使用
io_temp— 你永远不会忘记清理。 -
临时文件以读写权限打开。在读写之间切换时用
rewind或seek。 -
优先用
io_temp,而不是用普通文件 API 手动管理临时文件。 -
每种文件类型都接受
io_temp—native_file、obuf_file、iobuf_file、c_file等。