std::basic_istream<CharT,Traits>::read
提供: cppreference.com
<tbody>
</tbody>
basic_istream& read( char_type* s, std::streamsize count ); |
||
文字をストリームから抽出します。
UnformattedInputFunction として動作します。 sentry オブジェクトの構築および確認の後、文字を抽出し、それらを最初の要素が s によって指されている文字配列の連続する位置に格納します。 文字は以下の条件のいずれかが発生するまで抽出され格納されます。
count個の文字が抽出され格納された。
- 入力シーケンスでファイル終端条件が発生した (この場合
setstate(failbit|eofbit)が呼ばれます)。 抽出に成功した文字数は gcount() を使用して問い合わせることができます。
引数
| s | - | 文字を格納する文字配列へのポインタ |
| count | - | 読み込む文字数 |
戻り値
*this。
例外
エラーが発生し (エラー状態フラグが goodbit でなく)、その状態に対して投げるために exceptions() がセットされている場合は failure。
内部の操作が例外を投げた場合、それはキャッチされ、 badbit がセットされます。 exceptions() が badbit に対してセットされていれば、その例外が投げ直されます。
ノート
非変換ロケール (デフォルトのロケールは非変換です) を使用しているとき、 std::basic_ifstream のこの関数のオーバーライドはゼロコピーバルク I/O に最適化されているかもしれません (std::streambuf::xsgetn をオーバーライドすることによって)。
例
Run this code
#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;
if(raw.read(reinterpret_cast<char*>(&n), sizeof n))
std::cout << std::hex << std::showbase << n << '\n';
// prepare file for next snippet
std::ofstream("test.txt", std::ios::binary) << "abcd1\nabcd2\nabcd3";
// read entire file into string
if(std::ifstream is{"test.txt", std::ios::binary | std::ios::ate}) {
auto size = is.tellg();
std::string str(size, '\0'); // construct string to stream size
is.seekg(0);
if(is.read(&str[0], size))
std::cout << str << '\n';
}
}
出力:
0x12121212
abcd1
abcd2
abcd3
関連項目
| 文字のブロックを挿入します ( std::basic_ostream<CharT,Traits>のパブリックメンバ関数)
| |
| 書式付きデータを抽出します (パブリックメンバ関数) | |
| すでに利用可能な文字のブロックを抽出します (パブリックメンバ関数) | |
| 文字を抽出します (パブリックメンバ関数) | |
| 指定された文字が見つかるまで文字を抽出します (パブリックメンバ関数) | |
| ファイルから読み込みます (関数) |