#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAXTITL 40
#define MAXAUTL 40
#define MAXBKS 10
typedef struct book
{
char title[MAXTITL];
char author[MAXAUTL];
float value;
}Book;
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)
*find = '\0';
else
while (getchar() != '\n')
continue;
}
return ret_val;
}
int main()
{
Book library[MAXBKS];
int count = 0;
int index,filecount;
FILE* pbook;
int size = sizeof(Book);
if((pbook = fopen("book.dat","a+b")) == NULL)
{
fputs("can't open book.dat file\n",stderr);
exit(1);
}
rewind(pbook);
while(count < MAXBKS && fread(&library[count],size,1,pbook) == 1 )
{
if(count == 0)
puts("Current contents of book.dat:");
printf("%s by %s: $%.2f\n",library[count].title,
library[count].author,library[count].value);
count++;
}
filecount = count;
if(count == MAXBKS)
{
fputs("The book.dat file is full.",stderr);
exit(2);
}
puts("Please add new book titles.");
puts("Press [enter] at the start of a line to stop.");
while (count < MAXBKS && s_gets(library[count].title,MAXTITL) != NULL
&& library[count].title[0] != '\0')
{
puts("Now enter the author.");
s_gets(library[count].author,MAXAUTL);//输入字符串
puts("Now enter the value.");
scanf("%f",&library[count++].value);//输入数字
while (getchar() != '\n') //清理输入行
continue;
if(count < MAXBKS)
puts("Enter the next title.");
if(count >0)
{
puts("Here is the list of your books:");
for(index = 0;index < count; index++)
printf("%s by %s: $%.2f\n",library[count].title,
library[count].author,library[count].value);
fwrite(&library[filecount],size,count - filecount,pbook);
}
fclose(pbook);
return 0;
}
printf(" ");
return 0;
}
结构体综合应用
猜你喜欢
转载自blog.csdn.net/u014157109/article/details/120009434
今日推荐
周排行