第11.19章: 临时文件

English

概述

临时文件用于存放只需短暂存在的数据。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。

什么时候该用临时文件

临时文件适用于:

要点