首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

std::basic_istream::read

basic_istream& read( char_type* s, std::streamsize count );

?

?

从流中提取字符。

表现为UnformattedInputFunction.在构造和检查哨兵对象之后,提取字符并将它们存储到字符数组的连续位置,该字符数组的第一个元素由s提取和存储字符,直到出现下列任何情况:

  • count提取并存储字符
  • 文件结束条件发生在输入序列%28上,在这种情况下,setstate(failbit|eofbit)称为%29。成功提取的字符数可以使用Gcount%28%29...

参数

s

-

pointer to the character array to store the characters to

count

-

number of characters to read

返回值

*this...

例外

failure如果发生错误%28,则错误状态标志不是goodbit29%和exceptions()将被抛向那个州。

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

二次

代码语言:javascript
复制
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <cstdint>
 
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';
    }
}

二次

产出:

二次

代码语言:javascript
复制
0x12121212
abcd1
abcd2
abcd3

二次

另见

write

inserts blocks of characters (public member function of std::basic_ostream)

operator>>

extracts formatted data (public member function)

readsome

extracts already available blocks of characters (public member function)

get

extracts characters (public member function)

getline

extracts characters until the given character is found (public member function)

fread

reads from a file (function)

代码语言:txt
复制
 ? cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com