文章目录
- 1 函数原型
- 2 参数
- 3 返回值
- 4 示例
1 函数原型
fread():从与指定流stream相关联的二进制文件中读取数据块储存在str指向的内存空间中,函数原型如下:
size_t fread(const void *ptr, size_t size, size_t count, FILE *stream)
2 参数
fwrite()函数有四个参数:
- 参数ptr是指向某内存空间的指针,该内存空间用于储存从文件中读取的数据块;参数ptr类型为void*型,说明ptr可以指向任何数据类型;
- 参数size指定了每个从文件读取的数据项的字节大小,类型为size_t(unsigned int)型;
- 参数count指定了从文件读取的数据项的个数,类型为size_t(unsigned int)型;
- 参数stream是一个指向FILE类型结构的指针;参数stream指定了fread()函数要读取的文件流,等于fopen()函数的返回值。
3 返回值
fread()函数的返回值类型为size_t(unsigned int)型:
- 读取文件成功,返回成功读取文件的数据项个数,返回值应等于count;
- 读取文件失败,返回值小于count。
1. fread returns the number of full items actually read, which may be less than count if an error occurs or if the end of the file is encountered before reaching count.
4 示例
先写文件后读文件并打印,代码如下所示:
#define SIZE 20int main()
{//int arr1[SIZE] = { 0 };int arr2[SIZE] = { 0 };int count;for (count = 0; count < SIZE; count++){arr1[count] = 2 * count;}//FILE* fp;if ((fp = fopen("1.dat", "wb")) == NULL){printf("Failed to open file.\n");exit(1);}if ((fwrite(arr1, sizeof(arr1), 1, fp)) != 1){printf("Failed to write file.\n");exit(1);}fclose(fp);//if ((fp = fopen("1.dat", "rb")) == NULL){printf("Failed to open file.\n");exit(1);}if ((fread(arr2, sizeof(arr2), 1, fp)) != 1){printf("Failed to read file.\n");exit(1);}fclose(fp);//for (count = 0; count < SIZE; count++){printf("%d\t%d\n", arr1[count], arr2[count]);}return 0;
}
代码运行结果如下图所示: