In C++, read(buffer, count) copies count characters from an input stream into buffer. It reads spaces, new lines, and even zero bytes without stopping, and it adds no \0 at the end.
It is the matching function of write() and is mostly used for binary files and for reading data in fixed chunks. Include <iostream> to use it.
This is a member function of std::istream. You call it with a dot on a stream object, for example std::cin, std::cout, a file stream, or a std::stringstream. A stream is simply C++'s way to read or write data one piece after another.
Syntax
Call read on an input stream. Give the buffer and the number of characters you want.
C++
char buf[16];
in.read(buf, 16);
std::streamsize got = in.gcount(); // how many arrived
Call
What it does
in.read(buf, 5)
Reads five characters into buf.
in.read(reinterpret_cast<char*>(&n), sizeof n)
Reads the raw bytes of an int written by write().
while (in.read(buf, 4))
Reads full chunks of four. The loop stops when a full chunk cannot be read.
If fewer characters are available, read() stores what it can and sets eofbit and failbit. Ask gcount() how many arrived.
Library declarations
C++
istream& read(char_type* s, streamsize count);
Parameters
Parameter
Description
s
Required. A buffer that can hold at least count characters.
count
Required. The number of characters to read.
Return Value
Return Value
Description
istream&
A reference to the stream. It is false in a condition when fewer than count characters could be read.
C++ Examples
Example 1 — Read Five Characters
Read a block of text and add the final zero yourself.