雪铁龙c5新车多少钱:c++ 里 istream read()的用法

来源:百度文库 编辑:偶看新闻 时间:2024/04/30 11:14:27
c++里 istream read()的用法2010-05-19 19:18

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.

Additionaly, 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
#include
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;
}