命名空间
变体
操作

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

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

从流中提取字符。

行为如同 UnformattedInputFunction。在构造并检查 sentry 对象之后,提取字符并将它们存储到字符数组的连续位置,该数组的第一个元素由 s 指向。 字符被提取和存储,直到发生以下任一情况

  • count 个字符已被提取和存储。
  • 在输入序列上发生文件结束条件(在这种情况下,调用 setstate(failbit|eofbit))。可以使用 gcount() 查询成功提取的字符数。

目录

[edit] 参数

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

[edit] 返回值

*this

[edit] 异常

failure 如果发生错误(错误状态标志不是 goodbit)并且 exceptions() 设置为针对该状态抛出异常。

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

[edit] 注意

当使用非转换区域设置(默认区域设置是非转换的)时,std::basic_ifstream 中此函数的重写器可以针对零拷贝批量 I/O 进行优化(通过重写 std::streambuf::xsgetn)。

[edit] 示例

#include <cstdint>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
 
int main()
{
    // read() is often used for binary 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';
 
    // prepare file for next snippet
    std::ofstream("test.txt", std::ios::binary) << "abcd1\nabcd2\nabcd3";
 
    // read entire file into string
    if (std::ifstream is{"test.txt", std::ios::binary | std::ios::ate})
    {
        auto size = is.tellg();
        std::string str(size, '\0'); // construct string to stream size
        is.seekg(0);
        if (is.read(&str[0], size))
            std::cout << str << '\n';
    }
}

输出

0x12121212
abcd1
abcd2
abcd3

[edit] 参见

插入字符块
(std::basic_ostream<CharT,Traits> 的公共成员函数) [编辑]
提取格式化数据
(公共成员函数) [编辑]
提取已有的可用字符块
(公共成员函数) [编辑]
提取字符
(公共成员函数) [编辑]
提取字符直到找到给定的字符
(公共成员函数) [编辑]
从文件中读取
(函数) [编辑]