std::basic_istream<CharT,Traits>::read
From cppreference.com
< cpp | io | basic istream
| basic_istream& read( char_type* s, std::streamsize count ); |
||
ストリームから文字を抽出します。
UnformattedInputFunction として動作します。セントリーオブジェクトを構築してチェックした後、文字を抽出し、s が指す文字配列の連続した場所に格納します。以下のいずれかの条件が発生するまで、文字が抽出されて格納されます。
- count 文字が抽出され、格納された。
- 入力シーケンスでファイル終端条件が発生した(その場合、setstate(failbit|eofbit) が呼び出される)。正常に抽出された文字数は、gcount() を使用して照会できます。
目次 |
[編集] パラメータ
| s | - | 文字を格納する文字配列へのポインタ |
| count | - | 読み取る文字数 |
[編集] 戻り値
*this
[編集] 例外
failure: エラーが発生した場合(エラー状態フラグが goodbit ではない)で、exceptions() がその状態に対してスローするように設定されている場合。内部操作が例外をスローした場合、それはキャッチされ、badbit が設定されます。exceptions() が badbit に対して設定されている場合、例外は再スローされます。
[編集] 注記
変換を行わないロケール(デフォルトのロケールは変換を行いません)を使用する場合、std::basic_ifstream のこの関数のオーバーライドは、ゼロコピーバルク I/O(std::streambuf::xsgetn をオーバーライドすることによって)のために最適化される可能性があります。
[編集] 例
このコードを実行
#include <cstdint> #include <fstream> #include <iostream> #include <sstream> #include <string> 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> の public メンバ関数) | |
| 書式付きデータを抽出する (public member function) | |
| すでに利用可能な文字のブロックを抽出する (public member function) | |
| 文字を抽出する (public member function) | |
| 指定された文字が見つかるまで文字を抽出する (public member function) | |
| ファイルから読み込む (関数) |