From cppreference.com
basic_istream&read(char_type*s,std::streamsizecount);Extracts characters from stream.
Behaves as
. After constructing and checking the sentry object, extracts characters and stores them into successive locations of the character array whose first element is pointed to by s. Characters are extracted and stored until any of the following conditions occurs:
count characters were extracted and stored.
end of file condition occurs on the input sequence (in which case, setstate(failbit|eofbit) is called). The number of successfully extracted characters can be queried using
.
Parameters
s - pointer to the character array to store the characters to count - number of characters to read Return value
*this
Exceptions
if an error occurred (the error state flag is not
) and
is set to throw for that state.
If an internal operation throws an exception, it is caught and
is set. If
is set for badbit, the exception is rethrown.
Notes
When using a non-converting locale (the default locale is non-converting), the overrider of this function in
may be optimized for zero-copy bulk I/O (by means of overriding
).
Example
Run this code
#include<cstdint>#include<fstream>#include<iostream>#include<sstream>#include<string>intmain(){// read() is often used for binary I/Ostd::stringbin={'\x12','\x12','\x12','\x12'};std::istringstreamraw(bin);std::uint32_tn;if(raw.read(reinterpret_cast<char*>(&n),sizeofn))std::cout<<std::hex<<std::showbase<<n<<'\n';// prepare file for next snippetstd::ofstream("test.txt",std::ios::binary)<<"abcd1\nabcd2\nabcd3";// read entire file into stringif(std::ifstreamis{"test.txt",std::ios::binary|std::ios::ate}){autosize=is.tellg();std::stringstr(size,'\0');// construct string to stream sizeis.seekg(0);if(is.read(&str[0],size))std::cout<<str<<'\n';}}Output:
0x12121212 abcd1 abcd2 abcd3 See also
inserts blocks of characters
(public member function of std::basic_ostream<CharT,Traits>)
extracts formatted data
(public member function)
extracts already available blocks of characters
(public member function)
extracts characters
(public member function)
extracts characters until the given character is found
(public member function)
reads from a file
(function)