fread
来自 cppreference.cn
定义于头文件 <stdio.h> |
||
(until C99) | ||
(since C99) | ||
从给定输入流 stream 中读取最多 count 个对象到数组 buffer 中,如同为每个对象调用 fgetc size 次,并将结果按获得顺序存储到 buffer 的连续位置中,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"); // must use binary mode fwrite(a, sizeof *a, SIZE, fp); // writes an array of doubles fclose(fp); double b[SIZE]; fp = fopen("test.bin","rb"); const size_t ret_code = fread(b, sizeof b[0], SIZE, fp); // reads an array of doubles 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 // error handling { 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 函数 (页码: 待定)
- C17 标准 (ISO/IEC 9899:2018)
- 7.21.8.1 fread 函数 (页码: 243-244)
- C11 标准 (ISO/IEC 9899:2011)
- 7.21.8.1 fread 函数 (页码: 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
|