Namespaces
Variants

std::basic_istream<CharT,Traits>:: read

From cppreference.net
basic_istream & read ( char_type * s, std:: streamsize count ) ;

从流中提取字符。

表现为 非格式化输入函数 。在构造并检查哨兵对象后,提取字符并将其存储到以 s 指向的首元素为起点的字符数组中。字符将持续被提取和存储,直到满足以下任一条件:

  • count 个字符被提取并存储。
  • 当输入序列出现文件结束条件时(此时会调用 setstate ( failbit | eofbit ) )。成功提取的字符数量可通过 gcount() 查询。

目录

参数

s - 指向用于存储字符的字符数组的指针
count - 要读取的字符数量

返回值

* this

异常

failure if an error occurred (the error state flag is not goodbit ) and exceptions() is set to throw for that state.

如果内部操作抛出异常,该异常会被捕获并设置 badbit 。如果为 badbit 设置了 exceptions() ,则异常会被重新抛出。

注释

当使用非转换区域设置(默认区域设置为非转换)时, std::basic_ifstream 中此函数的重写可通过覆盖 std::streambuf::xsgetn 实现零拷贝批量 I/O 优化。

示例

#include <cstdint>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
int main()
{
    // read() 通常用于二进制 I/O
    std::string bin = {'\x12', '\x12', '\x12', '\x12'};
    std::istringstream raw(bin);
    std::uint32_t n;
    if (raw.read(reinterpret_cast<char*>(&n), sizeof n))
        std::cout << std::hex << std::showbase << n << '\n';
    // 为下一段代码准备文件
    std::ofstream("test.txt", std::ios::binary) << "abcd1\nabcd2\nabcd3";
    // 将整个文件读入字符串
    if (std::ifstream is{"test.txt", std::ios::binary | std::ios::ate})
    {
        auto size = is.tellg();
        std::string str(size, '\0'); // 构造与流大小相等的字符串
        is.seekg(0);
        if (is.read(&str[0], size))
            std::cout << str << '\n';
    }
}

输出:

0x12121212
abcd1
abcd2
abcd3

参见

插入字符块
( std::basic_ostream<CharT,Traits> 的公开成员函数)
提取格式化数据
(公开成员函数)
提取已可用的字符块
(公开成员函数)
提取字符
(公开成员函数)
提取字符直到发现指定字符
(公开成员函数)
从文件读取
(函数)