fread
来自cppreference.com
| 在标头 <stdio.h> 定义
|
||
| |
(C99 前) | |
| |
(C99 起) | |
从给定输入流 stream 读取至多 count 个对象到数组 buffer 中,如同以对每个对象调用 size 次 fgetc ,并按顺序存储结果到转译为 unsigned char 数组的 buffer 中的相继位置。流的文件位置指示器前进读取的字符数。
若出现错误,则流的文件位置指示器的结果值不确定。若读入部分的元素,则元素值不确定。
参数
| 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 The fread function (第 TBD 页)
- C17 标准(ISO/IEC 9899:2018):
- 7.21.8.1 The fread function (第 243-244 页)
- C11 标准(ISO/IEC 9899:2011):
- 7.21.8.1 The fread function (第 335 页)
- C99 标准(ISO/IEC 9899:1999):
- 7.19.8.1 The fread function (第 301 页)
- C89/C90 标准(ISO/IEC 9899:1990):
- 4.9.8.1 The fread function
参阅
(C11)(C11)(C11) |
从stdin、文件流或缓冲区读取格式化输入 (函数) |
| 从文件流获取一个字符串 (函数) | |
| 写入到文件 (函数) | |
fread 的 C++ 文档
| |