C++ basic_ios 库 - read
描述
它用于从流中提取 n 个字符,并将它们存储在 s 指向的数组中。
声明
以下是 std::basic_istream::read 的声明。
basic_istream& read (char_type* s, streamsize n);
参数
n − 要写入 s 的最大字符数(包括终止空字符)。
s − 指向存储提取字符的数组的指针。
返回值
返回 basic_istream 对象 (*this)。
异常
Basic guarantee − 如果抛出异常,则对象处于有效状态。
数据竞争
修改 s 指向的数组中的元素和流对象。
示例
在下面的 std::basic_istream::read 示例中。
#include <iostream>
#include <fstream>
int main () {
std::ifstream is ("test.txt", std::ifstream::binary);
if (is) {
is.seekg (0, is.end);
int length = is.tellg();
is.seekg (0, is.beg);
char * buffer = new char [length];
std::cout << "Reading " << length << " characters... ";
is.read (buffer,length);
if (is)
std::cout << "all characters read successfully.";
else
std::cout << "error: only " << is.gcount() << " could be read";
is.close();
delete[] buffer;
}
return 0;
}
输出应该是这样的 −
Reading 640 characters... all characters read successfully.

