第26.9章:I/O 操作

English

1. print、scan、transmit 下面的那一层

原始操作搬字符或字节,并报告搬了多少。它们不格式化、不解析、不选择缓冲区。 设备实现建立在它们之上;协议需要对一次读、一次写或一个偏移做精确控制时, 它们也是逃生口。

应用代码通常用 print、scan 和 transmit。 这三者处理格式化、带缓冲输入的向前看,以及零复制 staging。 本页的操作属于下面那一层,或者属于应用确实需要原始字节窗口的少数情况。

2. 读操作

操作 返回 含义
read_some(in, char* buf, count) std::size_t 最多读 count 个字符。返回读了多少;0 表示 EOF。
read_all(in, char* buf, count) void 读满 count 个字符,否则失败。
read_some_bytes(in, std::byte* buf, count) std::size_t 按字节寻址的形式;返回读了多少字节。
read_all_bytes(in, std::byte* buf, count) void 读满 count 字节,否则失败。

char buf[4096];
auto const n{::fast_io::operations::read_some(in, buf, sizeof(buf))};
if (n == 0)
{
    // end of input
}

read_some 是原语。即使后面还有数据,它也可能返回少于请求的数量。 read_all 是便利形式,会一直读到满足请求的数量。

3. 写操作

操作 返回 含义
write_some(out, char const* buf, count) std::size_t 最多写 count 个字符;返回接受了多少。
write_all(out, char const* buf, count) void 写完所有字符,否则失败。
write_some_bytes(out, std::byte const* buf, count) std::size_t 按字节寻址的形式;返回写了多少字节。
write_all_bytes(out, std::byte const* buf, count) void 写完所有字节,否则失败。

短写在管道和 socket 上是正常的。write_all 会循环到整个缓冲区被接受; write_some 让调用者决定未写后缀怎么处理。

4. 带偏移的操作

pread_* 和 pwrite_* 接受显式的 ::fast_io::intfpos_t 偏移。它们不消耗设备自己的位置; 这和 POSIX pread/pwrite 的区分相同。 多个读者或写者共享一个文件,或者在已知偏移修补记录时使用它们。

操作 返回 含义
pread_some(in, char* buf, count, off) std::size_t 在 off 读,不推进流位置。
pread_all(in, char* buf, count, off) void 在 off 读满 count 个字符。
pwrite_some(out, char const* buf, count, off) std::size_t 在 off 写,不推进流位置。
pwrite_all(out, char const* buf, count, off) void 在 off 写完所有字符。

*_bytes 形式用 std::byte*,偏移方式相同。 管道或 socket 不能 seek,所以传偏移是失败,不是悄悄退回。

5. Scatter 操作

scatter/gather 操作接受一个 ::fast_io::io_scatter_t 数组, 而不是一块连续缓冲区。每个条目是基址加长度。 这避免为了写出去而先把一组缓冲区复制成一块连续内存。


::fast_io::io_scatter_t parts[2]{
    {header.data(), header.size()},
    {body.data(), body.size()}};

::fast_io::operations::scatter_write_all(out, parts, 2);
家族 形式
读 scatter_read_some、scatter_read_all、 scatter_read_some_bytes、scatter_read_all_bytes
写 scatter_write_some、scatter_write_all、 scatter_write_some_bytes、scatter_write_all_bytes
带偏移读 scatter_pread_some、scatter_pread_all、 scatter_pread_some_bytes、scatter_pread_all_bytes
带偏移写 scatter_pwrite_some、scatter_pwrite_all、 scatter_pwrite_some_bytes、scatter_pwrite_all_bytes

*_some 形式返回 io_scatter_status_t, 指出在 scatter 数组中的位置和该条目内部的位置。 *_all 形式返回 void,整个 scatter 没有传完就失败。

6. Seek、刷新与单字符

操作 含义
io_stream_seek_bytes(stream, off, seekdir) 定位双向流;返回新位置。
input_stream_seek_bytes、output_stream_seek_bytes 方向特定的 seek。头文件侧。
input_stream_buffer_flush、output_stream_buffer_flush、 io_stream_buffer_flush 刷新缓冲数据。头文件侧。
char_put(out, ch) 写一个字符。头文件侧。

seekdir 是 beg、cur 或 end。 带缓冲的流会在 seek 前刷新或调整缓冲区, 所以你拿回的位置是设备将使用的位置,不是过期的缓冲区游标。

7. 失败与部分进展

这些操作都通过 herbception 报告设备失败。some 和 all 的区别就是部分进展策略:

8. 模块导出边界

fast_io 模块导出读、写、pread、pwrite 和 scatter 家族, 以及 io_stream_seek_bytes。方向特定的 seek 形式、 缓冲区刷新操作、char_put 和部分引用访问器目前属于头文件侧。 这些用 #include <fast_io.h>。

不要在这里搭应用代码。 除非你在实现设备或 fast_io 下面的一层,否则用 print、 scan 和 transmit。原始操作把缓冲区记账工作推回给你。

要点