把结构内容保存到文件当中【使用fread()和fwrite()函数读写结构大小的单元,储存记录最没效率的方法是用fprintf()】

程序

library[count].title :对结构体数组进行理解

//把结构内容保存到文件当中
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define LEN 100
#define MAXTITL 40
#define MAXAUTL 40
#define MAXBKS 10/* 最大书籍数量 */

char * s_gets(char * st, int n);

struct book //建立书本的模板
{

	char title[MAXTITL];
	char anthor[MAXAUTL];
	float value;
};

int main(void)
{
	struct book library[MAXBKS];//结构数组
	int count = 0;
	int index, filecount;
	FILE *pbooks;
	int size = sizeof(struct book);//统计结构体大小,方便读写操作

	if ((pbooks = fopen("book.tat", "a+b")) == NULL)
	{
		fputs("Can't open book.dat file\n", stderr);
		exit(EXIT_FAILURE);
	}

	rewind(pbooks);
	//先读取一下书本内容,并理一下统计了几本书
	//
	while (count < MAXBKS && fread(&library[count], size, 1, pbooks) == 1)
	{
		if (count == 0)
		{
			fputs("The book.dat file is null.", stderr);
		}
		else
		{
			puts("Current contents of book.dat:");
			printf("%s by %s : $%.2f\n", library[count].title, library[count].anthor, library[count].value);
			count++;
		}
		
	}

	filecount = count;//已有几本书
	if (count == MAXBKS)
	{
		fputs("The book.dat file is full.", stderr);
		exit(3);
	}

	puts("Please add new book titles."); 
	puts("在行的开头按[enter]停止。");
	while (count < MAXBKS && s_gets(library[count].title, MAXTITL) != NULL && library[count].title[0] != '\0')
	{
		puts("Now enter the author.");
		s_gets(library[count].anthor , MAXAUTL);
		puts("Now enter the value.");
		scanf("%f", &library[count++].value);//count++ :每次都输入价格,单独一行进行count++也可以

		while (getchar() != '\n')//
			continue;

		if (count < MAXBKS)
		{
			puts("Enter the next title.");
		}
	}

	if (count > MAXBKS)//
	{
		puts("Here is the list of your books:");
		for (index = 00; index < count; index++)//先显示出来再入文件
		{
			printf("%s by %s: $%.2f\n", library[index].title, library[index].anthor, library[index].value);
			fwrite(&library[filecount], size, count - filecount, pbooks);
				//filecount : 从当前位置开始追加; count - filecount :只写追加的书
		}
	}
	else
		puts("No books? Too bad.\n");

	puts("Bye.\n");
	fclose(pbooks);


	exit(0);
}

char * s_gets(char * st, int n) 
{
	char * ret_val; 
	char * find; 
	ret_val = fgets(st, n, stdin); 
	if (ret_val) 
	{
		find = strchr(st, '\n'); // 查找换行符

		if (find)// 如果地址不是 NULL,
			*find = '\0'; // 在此处放置一个空字符1077
		else
			while(getchar() != '\n')
				continue;// 清理输入行
	}
	return ret_val;
}

.
.
.

辅助理解

在这里插入图片描述在这里插入图片描述
.
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

扳手的海角

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值