第11.7章: 随机访问 I/O
定位操作
fast_io 在 ::fast_io::operations 命名空间中提供移动文件位置的定位操作。用哪一个取决于文件的方向:
::fast_io::operations::input_stream_seek— 用于输入文件(ibuf_file)。::fast_io::operations::output_stream_seek— 用于输出文件(obuf_file)。::fast_io::operations::io_stream_seek— 用于双向文件(iobuf_file)。
此外还有 _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 命名空间:
::fast_io::operations::pwrite_some/pwrite_all— 按位置写入。::fast_io::operations::pread_some/pread_all— 按位置读取。::fast_io::operations::pwrite_some_bytes/pwrite_all_bytes— 针对::std::byte的按位置写入。::fast_io::operations::pread_some_bytes/pread_all_bytes— 针对::std::byte的按位置读取。
调用之后文件位置保持不变。
用 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章。
要点
- 用
::fast_io::operations::input_stream_seek、output_stream_seek或io_stream_seek移动文件位置。 - 按位置写入用
::fast_io::operations::pwrite_all— 在指定偏移处写,且不改变文件位置。 - 按位置读取用
::fast_io::operations::pread_all。