std::basic_istream::read

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

Extracts characters from stream.

Behaves as UnformattedInputFunction. 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 gcount().

Parameters

s - pointer to the character array to store the characters to
count - number of characters to read

Return value

*this.

Exceptions

failure if an error occurred (the error state flag is not goodbit) and exceptions() is set to throw for that state.

If an internal operation throws an exception, it is caught and badbit is set. If exceptions() is set for badbit, the exception is rethrown.

Example

#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;
    raw.read(reinterpret_cast<char*>(&n), sizeof n);
    std::cout << std::hex << std::showbase << n << '\n';
 
    // prepare file for next snippet
    std::ofstream os("test.txt", std::ofstream::binary);
    for (unsigned i = 0; i < 10; i++) { // prepare stream
        os << "abcd" << i << "\n";
    }
    os.close();
 
    // read entire file into string
    std::ifstream is("test.txt", std::ifstream::binary);
    if (is) {
        // get length of file:
        is.seekg(0, is.end);
        int length = is.tellg();
        is.seekg(0, is.beg);
 
        std::string str;
        str.resize(length, ' '); // reserve space
        char* begin = &*str.begin();
 
        is.read(begin, length);
        is.close();
 
        std::cout << str << "\n";
    } else {
        std::cout << "Could not open test.txt\n";
    }
}

Output:

0x12121212
abcd0
abcd1
abcd2
abcd3
abcd4
abcd5
abcd6
abcd7
abcd8
abcd9

See also

inserts blocks of characters
(public member function of std::basic_ostream)
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)
doc_CPP
2016-10-11 10:00:56
Comments
Leave a Comment

Please login to continue.