第11.7章: 随机访问 I/O

English

定位操作

fast_io 在 ::fast_io::operations 命名空间中提供移动文件位置的定位操作。用哪一个取决于文件的方向:

此外还有 _rewind 变体用于回到开头,以及直接接受字节偏移的 _seek_bytes 变体。


#include <fast_io.h>
#include <fast_io_device.h>

int main()
{
    using namespace ::fast_io::iomnp;
    ::fast_io::obuf_file obf(u8"seekable.txt", ::fast_io::open_mode::out);

    // Write some data
    println(obf, "Hello, World!");

    // Seek back to the beginning (output_stream_rewind)
    ::fast_io::operations::output_stream_rewind(obf);

    // Or seek to a specific offset
    ::fast_io::operations::output_stream_seek(obf, 0);
}
      

按位置 I/O(pwrite/pread)

按位置 I/O 让你读写文件中某个特定偏移处的内容,而不改变文件当前的位置。它等价于 POSIX 的 pread(2) 与 pwrite(2)。

在 fast_io 中,使用 operations 命名空间:

调用之后文件位置保持不变。

用 pwrite 做随机写


#include <fast_io.h>
#include <fast_io_device.h>

int main()
{
    using namespace ::fast_io::iomnp;
    ::fast_io::obuf_file obf(u8"positional_write.txt", ::fast_io::open_mode::out);

    // Write at specific offsets without disturbing file position
    ::fast_io::operations::pwrite_all(obf, "AAAA", 0uz);
    ::fast_io::operations::pwrite_all(obf, "BBBB", 100uz);
    ::fast_io::operations::pwrite_all(obf, "CCCC", 200uz);
}
      

这个程序运行结束后,文件在偏移 0 处是 "AAAA",偏移 100 处是 "BBBB",偏移 200 处是 "CCCC"。文件位置不受 pwrite 调用影响。

用 pread 做随机读


#include <fast_io.h>
#include <fast_io_device.h>

int main()
{
    using namespace ::fast_io::iomnp;
    ::fast_io::ibuf_file ibf(u8"positional_write.txt", ::fast_io::open_mode::in);

    char buf1[5]{};
    char buf2[5]{};

    // Read from specific offsets
    ::fast_io::operations::pread_all(ibf, ::fast_io::as_bytes(::fast_io::span{buf1, 4uz}), 0uz);
    ::fast_io::operations::pread_all(ibf, ::fast_io::as_bytes(::fast_io::span{buf2, 4uz}), 100uz);

    println("At offset 0:   ", ::fast_io::mnp::os_c_str(buf1));
    println("At offset 100: ", ::fast_io::mnp::os_c_str(buf2));
}
      

线程安全

如果多个线程需要并发写同一个文件,请使用像 ::fast_io::obuf_file_lockable 这样的可加锁文件类型。锁定它、取得未加锁的句柄,然后使用该句柄以获得更好的性能。见第11.6章。

要点