std:: fread
| I/O manipulators | ||||
| Print functions (C++23) | ||||
| C-style I/O | ||||
| Buffers | ||||
|
(C++23)
|
||||
|
(
C++98/26*
)
|
||||
|
(C++20)
|
||||
| Streams | ||||
| Abstractions | ||||
| File I/O | ||||
| String I/O | ||||
| Array I/O | ||||
|
(C++23)
|
||||
|
(C++23)
|
||||
|
(C++23)
|
||||
|
(
C++98/26*
)
|
||||
|
(
C++98/26*
)
|
||||
|
(
C++98/26*
)
|
||||
| Synchronized Output | ||||
|
(C++20)
|
||||
| Types | ||||
| Error category interface | ||||
|
(C++11)
|
||||
|
(C++11)
|
| Types and objects | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Functions | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
ヘッダーで定義
<cstdio>
|
||
|
std::
size_t
fread
(
void
*
buffer,
std::
size_t
size,
std::
size_t
count,
std::
FILE
*
stream
)
;
|
||
最大で count 個のオブジェクトを配列 buffer に、指定された入力ストリーム stream から読み込む。各オブジェクトに対して std::fgetc を size 回呼び出すのと同様に動作し、得られた結果を順次 buffer の連続する位置に格納する。この際 unsigned char の配列として再解釈される。ストリームのファイル位置指示子は、読み込まれた文字数分だけ進められる。
オブジェクトが TriviallyCopyable でない場合、動作は未定義です。
エラーが発生した場合、ストリームのファイル位置指示子の結果の値は不定です。部分的な要素が読み込まれた場合、その値は不定です。
目次 |
パラメータ
| buffer | - | 読み取る配列の最初のオブジェクトへのポインタ |
| size | - | オブジェクトのサイズ(バイト単位) |
| count | - | 読み取るオブジェクトの数 |
| stream | - | 読み取り元の入力ファイルストリーム |
戻り値
正常に読み込まれたオブジェクトの数。エラーまたはEOF(end-of-file)状態が発生した場合、 count より少なくなる可能性があります。
size
または
count
がゼロの場合、
fread
はゼロを返し、それ以外の動作は行いません。
fread
はEOFとエラーを区別せず、呼び出し側は
std::feof
と
std::ferror
を使用してどちらが発生したかを判定する必要があります。
例
#include <cstddef> #include <cstdio> #include <fstream> #include <iomanip> #include <iostream> #include <vector> int main() { // ファイルの準備 std::ofstream("test.txt") << 1 << ' ' << 2 << '\n'; std::FILE* f = std::fopen("test.txt", "r"); std::vector<char> buf(4); // charはtrivially copyable const std::size_t n = std::fread(&buf[0], sizeof buf[0], buf.size(), f); std::cout << "Read " << n << " object" << (n > 1 ? "s" : "") << ": " << std::hex << std::uppercase << std::setfill('0'); for (char n : buf) std::cout << "0x" << std::setw(2) << static_cast<short>(n) << ' '; std::cout << '\n'; std::vector<std::string> buf2; // stringはtrivially copyableではない // これは未定義動作を引き起こす: // std::fread(&buf2[0], sizeof buf2[0], buf2.size(), f); }
出力例:
Read 4 objects: 0x31 0x20 0x32 0x0A
関連項目
|
書式付き入力を
stdin
、ファイルストリーム、またはバッファから読み込む
(関数) |
|
|
ファイルストリームから文字列を取得する
(関数) |
|
|
ファイルに書き込む
(関数) |
|
|
Cドキュメント
for
fread
|
|