在线文档教程
C++
输入/输出 | Input/output

std::basic_istream::read

性病:基本[医]iStream::

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,异常将被重新抛出。

二次

#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'; } }

二次

产出:

二次

0x12121212 abcd1 abcd2 abcd3

二次

另见

writeinserts blocks of characters (public member function of std::basic_ostream)
operator>>extracts formatted data (public member function)
readsomeextracts already available blocks of characters (public member function)
getextracts characters (public member function)
getlineextracts characters until the given character is found (public member function)
freadreads from a file (function)

© cppreference.com

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

http://en.cppreference.com/w/cpp/io/basic[医]iStream/读