Namespaces
Variants

std::basic_istream<CharT,Traits>:: read

From cppreference.net
basic_istream & read ( char_type * s, std:: streamsize count ) ;
**翻訳結果:**
basic_istream & read ( char_type * s, std:: streamsize count ) ;
**注記:** 指定された要件に従い、HTMLタグ、属性、` `/`
`/``タグ内のテキスト、およびC++固有の用語(`basic_istream`, `read`, `char_type`, `std::streamsize`など)は翻訳せず、元のフォーマットを保持しています。このコードはC++の関数宣言であり、翻訳対象となる自然言語テキストは含まれていません。

ストリームから文字を抽出します。

UnformattedInputFunction として振る舞う。セントリオブジェクトを構築・チェックした後、文字を抽出し、 s が指す先頭要素から連続する文字配列の位置に格納する。以下のいずれかの条件が発生するまで、文字の抽出と格納が継続される:

  • count 文字が抽出され保存されました。
  • 入力シーケンスでファイル終端条件が発生した場合(この場合、 setstate ( failbit | eofbit ) が呼び出される)。正常に抽出された文字数は gcount() を使用して問い合わせることができる。

目次

パラメータ

s - 文字を格納する文字配列へのポインタ
count - 読み込む文字数

戻り値

* this

例外

failure if an error occurred (the error state flag is not goodbit ) and exceptions() is set to throw for that state.

内部操作が例外をスローした場合、それは捕捉され、 badbit が設定されます。 exceptions() badbit に対して設定されている場合、例外は再スローされます。

注記

非変換ロケールを使用する場合(デフォルトロケールは非変換です)、この関数のオーバーライドは std::basic_ifstream において、ゼロコピーバルクI/O用に最適化される可能性があります( std::streambuf::xsgetn のオーバーライドによる)。

#include <cstdint>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
int main()
{
    // read() はバイナリ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';
    // 次のスニペット用にファイルを準備
    std::ofstream("test.txt", std::ios::binary) << "abcd1\nabcd2\nabcd3";
    // ファイル全体を文字列に読み込む
    if (std::ifstream is{"test.txt", std::ios::binary | std::ios::ate})
    {
        auto size = is.tellg();
        std::string str(size, '\0'); // ストリームサイズに合わせて文字列を構築
        is.seekg(0);
        if (is.read(&str[0], size))
            std::cout << str << '\n';
    }
}

出力:

0x12121212
abcd1
abcd2
abcd3

関連項目

文字ブロックを挿入する
( std::basic_ostream<CharT,Traits> の公開メンバ関数)
書式化されたデータを抽出する
(公開メンバ関数)
利用可能な文字ブロックを抽出する
(公開メンバ関数)
文字を抽出する
(公開メンバ関数)
指定された文字が見つかるまで文字を抽出する
(公開メンバ関数)
ファイルから読み込む
(関数)