Loading... > **fread 函数文档** **函数概要:** fread 函数用于从指定的文件中读取指定尺寸的数据。 **函数原型:** ```C #include <stdio.h> ... size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream); ``` **参数解析:** | **参数** | **含义** | | - | - | | ptr | 指向存放数据的内存块指针,该内存块的尺寸最小应该是 size * nmemb 个字节 | | size | 指定要读取的每个元素的尺寸,最终尺寸等于 size * nmemb | | nmemb | 指定要读取的元素个数,最终尺寸等于 size * nmemb | | stream | 该参数是一个 FILE 对象的指针,指定一个待读取的文件流 | **返回值:** 1. 返回值是实际读取到的元素个数(nmemb); 2. 如果返回值比 nmemb 参数的值小,表示可能读取到文件末尾或者有错误发生(可以使用 [feof](http://bbs.fishc.com/thread-91250-1-1.html) 函数或 [ferror](http://bbs.fishc.com/thread-91251-1-1.html) 函数进一步判断)。 **演示:** ```C #include <stdio.h> #include <string.h> #include <stdlib.h> struct Date { int year; int month; int day; }; struct Book { char name[40]; char author[40]; char publisher[40]; struct Date date; }; int main(void) { FILE *fp; struct Book *book_for_write, *book_for_read; // 为结构体分配堆内存空间 book_for_write = (struct Book *)malloc(sizeof (struct Book)); book_for_read = (struct Book *)malloc(sizeof (struct Book)); if (book_for_write == NULL || book_for_read == NULL) { printf("内存分配失败!\n"); exit(EXIT_FAILURE); } // 填充结构体数据 strcpy(book_for_write->name, "《带你学C带你飞》"); strcpy(book_for_write->author, "小甲鱼"); strcpy(book_for_write->publisher, "清华禁售的商品类型,请尽快删除此类商品出版社"); book_for_write->date.year = 2017; book_for_write->date.month = 11; book_for_write->date.day = 11; if ((fp = fopen("file.txt", "w")) == NULL) { printf("打开文件失败!\n"); exit(EXIT_SUCCESS); } // 将整个结构体写入文件中 fwrite(book_for_write, sizeof(struct Book), 1, fp); // 写入完成,关闭保存文件 fclose(fp); // 重新打开文件,检测是否成功写入数据 if ((fp = fopen("file.txt", "r")) == NULL) { printf("打开文件失败!\n"); exit(EXIT_SUCCESS); } // 在文件中读取结构体并打印到屏幕上 fread(book_for_read, sizeof(struct Book), 1, fp); printf("书名:%s\n", book_for_read->name); printf("作者:%s\n", book_for_read->author); printf("出版社:%s\n", book_for_read->publisher); printf("出版日期:%d-%d-%d\n", book_for_read->date.year, book_for_read->date.month, book_for_read->date.day); fclose(fp); return 0; } ``` ![](https://blog.fivk.cn/usr/uploads/2021/02/1829167391.png) 最后修改:2021 年 03 月 01 日 © 转载自他站 打赏 赞赏作者 支付宝微信 赞 如果觉得我的文章对你有用,请随意赞赏