Skip to content

Commit 3a5b8ac

Browse files
committed
new page fread.md
1 parent f2c2262 commit 3a5b8ac

File tree

2 files changed

+81
-1
lines changed

2 files changed

+81
-1
lines changed

reference/cstdio.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@
5454
| [`fgets`](/reference/cstdio/fgets.md) | ファイルからN文字入力する | |
5555
| [`fputc`](/reference/cstdio/fputc.md) | ファイルに1文字出力する | |
5656
| [`fputs`](/reference/cstdio/fputs.md) | ファイルにN文字出力する | |
57-
| [`fread`](/reference/cstdio/fread.md.nolink) | ファイルからN文字読み込む | |
57+
| [`fread`](/reference/cstdio/fread.md) | ファイルからN文字読み込む | |
5858
| [`fwrite`](/reference/cstdio/fwrite.md.nolink) | ファイルにN文字書き込む | |
5959
| [`fgetpos`](/reference/cstdio/fgetpos.md.nolink) | ファイルの現在位置を取得する | |
6060
| [`fseek`](/reference/cstdio/fseek.md.nolink) | ファイルの現在位置を移動する | |

reference/cstdio/fread.md

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
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

Comments
 (0)