fread -- 从文件中读取数据
fread 函数文档函数概要:
fread 函数用于从指定的文件中读取指定尺寸的数据。
函数原型:
#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 函数或 ferror 函数进一步判断)。
演示:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct Date
{
int year;
int month;
int day;
};
struct Book
{
char name;
char author;
char publisher;
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;
}
{:5_102:}{:10_266:}x小甲鱼大大什么时候更新作业 打卡 小甲鱼牛逼哟{:10_254:} 打卡
页:
[1]