fread
|
定义于头文件
<stdio.h>
|
||
| (C99前) | ||
| (C99起) | ||
从给定的输入流 stream 中读取最多 count 个对象到数组 buffer 中,其过程类似于对每个对象调用 size 次 fgetc ,并将按顺序获取的结果存储到 buffer 的连续位置中(该缓冲区被重新解释为 unsigned char 数组)。流的文件位置指示器按读取的字符数前进。
如果发生错误,流的文件位置指示符的最终值是不确定的。如果读取了部分元素,其值也是不确定的。
目录 |
参数
| buffer | - | 指向存储读取对象的数组的指针 |
| size | - | 每个对象的字节大小 |
| count | - | 要读取的对象数量 |
| stream | - | 要读取的流 |
返回值
成功读取的对象数量,可能少于 count ,若出现错误或文件结束条件。
如果
size
或
count
为零,
fread
函数将返回零且不执行任何其他操作。
fread
不会区分文件结束和错误,调用方必须使用
feof
和
ferror
来确定发生了哪种情况。
示例
#include <stdio.h> enum { SIZE = 5 }; int main(void) { const double a[SIZE] = {1.0, 2.0, 3.0, 4.0, 5.0}; printf("Array has size %ld bytes, element size: %ld\n", sizeof a, sizeof *a); FILE *fp = fopen("test.bin", "wb"); // 必须使用二进制模式 fwrite(a, sizeof *a, SIZE, fp); // 写入一个 double 类型数组 fclose(fp); double b[SIZE]; fp = fopen("test.bin","rb"); const size_t ret_code = fread(b, sizeof b[0], SIZE, fp); // 读取一个 double 类型数组 if (ret_code == SIZE) { printf("Array at %p read successfully, contents:\n", (void*)&a); for (int n = 0; n != SIZE; ++n) printf("%f ", b[n]); putchar('\n'); } else // 错误处理 { if (feof(fp)) printf("Error reading test.bin: unexpected end of file\n"); else if (ferror(fp)) perror("Error reading test.bin"); } fclose(fp); }
可能的输出:
Array has size 40 bytes, element size: 8 Array at 0x1337f00d6960 read successfully, contents: 1.000000 2.000000 3.000000 4.000000 5.000000
参考文献
- C23 标准 (ISO/IEC 9899:2024):
-
- 7.21.8.1 fread 函数 (页: TBD)
- C17 标准 (ISO/IEC 9899:2018):
-
- 7.21.8.1 fread 函数 (页: 243-244)
- C11 标准 (ISO/IEC 9899:2011):
-
- 7.21.8.1 fread 函数 (p: 335)
- C99标准(ISO/IEC 9899:1999):
-
- 7.19.8.1 fread函数(页数:301)
- C89/C90 标准 (ISO/IEC 9899:1990):
-
- 4.9.8.1 fread 函数
参见
|
(C11)
(C11)
(C11)
|
从
stdin
、文件流或缓冲区读取格式化输入
(函数) |
|
从文件流获取字符串
(函数) |
|
|
写入文件
(函数) |
|
|
C++ 文档
关于
fread
|
|