C stdio fread() 函数
示例
从文件中读取一些数据:
FILE *fptr;
fptr = fopen("filename.txt", "r");
char data[20];
int n = fread(data, 1, 19, fptr);
// printf() and other string
functions need to find a null terminating character
data[n] = '\0';
printf("%s", data);
fclose(fptr);
定义和用法
fread() 函数从文件中读取数据并写入内存块。
fread() 函数定义在 <stdio.h> 头文件中。
语法
fread(void * destination, size_t size, size_t amount, FILE * fptr);
size_t 数据类型为非负整数。
参数值
| 参数 | 描述 |
|---|---|
| destination | 必需。指向要写入数据的内存块的指针。 |
| size | 必需。内存块中元素的大小。 |
| amount | 必填项。要从文件中读取并写入内存块的元素数量。 |
| fptr | 必需。文件指针,通常由 fopen() 函数创建。 |
技术细节
| 返回值: | 一个表示已读取元素数量的 size_t 值。如果此数字与 `amount` 参数不同,则表示已到达文件末尾或发生错误。 |
|---|

