|
| 1 | +# fread |
| 2 | +* cstdio[meta header] |
| 3 | +* std[meta namespace] |
| 4 | +* function[meta id-type] |
| 5 | + |
| 6 | +```cpp |
| 7 | +namespace std { |
| 8 | + std::size_t fread(void *buffer, std::size_t size, std::size_t count, std::FILE *stream); |
| 9 | +} |
| 10 | +``` |
| 11 | +
|
| 12 | +## 概要 |
| 13 | +ファイルから`count`文字の`size`バイトのデータを読み込む。 |
| 14 | +
|
| 15 | +ファイル内の位置は、読み取られたバイトだけ進む。 |
| 16 | +
|
| 17 | +## 要件 |
| 18 | +- `buffer`は有効なポインタであること。 |
| 19 | +- `size`は0より大きいこと。 |
| 20 | +- `count`は0より大きいこと。 |
| 21 | +- `stream`は有効なファイルストリームであること。 |
| 22 | +
|
| 23 | +## 戻り値 |
| 24 | +正常に読み込むことのできた項目の数を返す。 |
| 25 | +
|
| 26 | +`size`または`count`のいずれかが0だった場合、必ず`0`を返し、`buffer`は変更されない。 |
| 27 | +
|
| 28 | +## 効果 |
| 29 | +`stream`から`count`個の`size`バイトのデータを読み込む。 |
| 30 | +
|
| 31 | +読み込んだデータは、`buffer`が指すメモリの先頭から順に格納される。 |
| 32 | +
|
| 33 | +読み込んだデータの長さは、`count * size`バイトである。 |
| 34 | +
|
| 35 | +## 例 |
| 36 | +```cpp example |
| 37 | +#include <cstdio> |
| 38 | +
|
| 39 | +int main() { |
| 40 | + std::FILE *file = std::fopen("sample.txt", "r"); |
| 41 | + if (!file) { |
| 42 | + std::perror("ファイルを開けませんでした"); |
| 43 | + return 1; |
| 44 | + } |
| 45 | +
|
| 46 | + char buffer[100]; |
| 47 | + /* |
| 48 | + 厳密には、sizeof(char)は1バイトであることが保証されているため、 |
| 49 | + sizeof(buffer) / sizeof(char)は、bufferの要素数と等しくなる。 |
| 50 | + */ |
| 51 | + std::size_t count = std::fread(buffer, sizeof(char), sizeof(buffer) / sizeof(char), file); |
| 52 | + std::printf("読み込んだデータの長さ: %zu\n", count); |
| 53 | +
|
| 54 | + std::fclose(file); |
| 55 | + return 0; |
| 56 | +} |
| 57 | +``` |
| 58 | +* std::fread()[color ff0000] |
| 59 | +* std::fopen()[link /reference/cstdio/fopen.md] |
| 60 | +* std::fclose()[link /reference/cstdio/fclose.md] |
| 61 | +* std::perror()[link /reference/cstdio/perror.md.nolink] |
| 62 | +* std::printf()[link /reference/cstdio/printf.md] |
| 63 | + |
| 64 | +### ファイル内容(sample.txt) |
| 65 | +``` |
| 66 | +Hello, World! |
| 67 | +``` |
| 68 | + |
| 69 | +### 出力例 |
| 70 | +``` |
| 71 | +読み込んだデータの長さ: 14 |
| 72 | +``` |
| 73 | + |
| 74 | +## 処理系 |
| 75 | +- [Clang](/implementation.md#clang): ?? |
| 76 | +- [GCC](/implementation.md#gcc): ?? |
| 77 | +- [Visual C++](/implementation.md#visual_cpp): ?? |
| 78 | + |
| 79 | +## 参照 |
| 80 | +- [sizeof演算子にまつわるアレコレ](https://qiita.com/yohhoy/items/a2ab2900a2bd36c31879) |
0 commit comments