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

来自cppreference.com
< cpp‎ | io‎ | basic istream
 
 
 
 
basic_istream& read( char_type* s, std::streamsize count );

从流提取字符。

表现为无格式输入函数 (UnformattedInputFunction) 。构造并检查 sentry 对象后,提取字符并将它们存储到以 s 指向其首元素的字符数组中的相继位置。提取并存储字符,直至出现任何下列条件:

  • 提取并存储了 count 个字符
  • 输入序列上发生文件尾条件(该情况下调用 setstate(failbit|eofbit))。成功提取的字符数能用 gcount() 查询。

参数

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

返回值

*this

异常

在出现错误(错误状态标志不是 goodbit)并且 exceptions() 已设置为对该状态抛出时,会抛出 failure

如果内部操作抛出了异常,那么捕获它并设置 badbit。如果 exceptions() 设置了 badbit,那么就会重抛该异常。

注解

使用非转换的本地环境时(默认本地环境为非转换),此函数在 std::basic_ifstream 中的覆写函数可以针对零复制的大块 I/O 进行优化(通过覆写 std::streambuf::xsgetn)。

示例

#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";
 
    // 读取整个文件到 string
    if(std::ifstream is{"test.txt", std::ios::binary | std::ios::ate}) {
        auto size = is.tellg();
        std::string str(size, '\0'); // 构造 string 为流大小
        is.seekg(0);
        if(is.read(&str[0], size))
            std::cout << str << '\n';
    }
}

输出:

0x12121212
abcd1
abcd2
abcd3

参阅

按区块插入字符
(std::basic_ostream<CharT,Traits> 的公开成员函数)
提取带格式数据
(公开成员函数)
提取已经可用的字符区块
(公开成员函数)
提取字符
(公开成员函数)
持续提取字符,直到找到给定字符
(公开成员函数)
从文件读取
(函数)