程序
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;
}
.
.
.
辅助理解
.