|
istream& read ( char* s, streamsize n );
Read block of data
Reads a block of data of n characters and stores it in the array pointed by s.
If the End-of-File is reached before n characters have been read, the array will contain all the elements read until it, and the failbit and eofbit will be set (which can be checked with members fail and eof respectively).
Notice that this is an unformatted input function and what is extracted is not stored as a c-string format, therefore no ending null-character is appended at the end of the character sequence.
Calling member gcount after this function the total number of characters read can be obtained.
Parameters
- s
- Pointer to an allocated block of memory where the content read will be stored.
- n
- Integer value of type streamsize representing the size in characters of the block of data to be read.
Return Value
The functions return *this.
Errors are signaled by modifying the internal state flags:
flag | error |
eofbit | The end of the source of characters is reached before n characters have been read. This also sets failbit. |
failbit | The end of the source of characters is reached before n characters have been read. This also sets eofbit. |
badbit | An error other than the above happened. |
Additionally, in any of these cases, if the appropriate flag has been set with member function ios::exceptions, an exception of type ios_base::failure is thrown.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
// read a file into memory
#include <iostream>
#include <fstream>
using namespace std;
int main () {
int length;
char * buffer;
ifstream is;
is.open ("test.txt", ios::binary );
// get length of file:
is.seekg (0, ios::end);
length = is.tellg();
is.seekg (0, ios::beg);
// allocate memory:
buffer = new char [length];
// read data as a block:
is.read (buffer,length);
is.close();
cout.write (buffer,length);
delete[] buffer;
return 0;
}
|
Basic template member declaration
( basic_istream<charT,traits> )
1 2
|
typedef charT char_type;
basic_istream& read ( char_type* s, streamsize n );
|
See also
istream::get | Get unformatted data from stream (public member function) |
istream::readsome | Read block of data available in the buffer (public member function) |
|