#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAXTITL 40
#define MAXAUTL 40
#define MAXBKS 10
char* s_gets(char* st, int n);
struct book {
char title[MAXTITL];
char author[MAXAUTL];
float value;
_Bool is_deleted;
};
int main(void)
{
static struct book library[MAXBKS];
struct book temp;
int count = 0;
int index, filecount;
FILE* pbooks;
int size = sizeof(struct book);
char choice;
if ((pbooks = fopen("book.txt", "r+b")) == NULL)
{
fputs("Can't open book.txt file\n", stderr);
exit(1);
}
rewind(pbooks);
while (count < MAXBKS && fread(&library[count], size, 1,
pbooks) == 1)
{
if (count == 0)
puts("Current contents of book.txt:");
if (library[count].is_deleted == 1)
continue;
printf("%s by %s: $%.2f\n", library[count].title,
library[count].author, library[count].value);
count++;
}
filecount = count;
if (count == MAXBKS)
{
fputs("The book.txt file is full.", stderr);
exit(2);
}
while (1)
{
puts("Input A to add a new book in the list.\nInput C to"
" change a book in the list.\nInput D to delete a book in"
"the list.\nIn input Q to quit");
while (scanf("%c", &choice) != 1 || !(strchr("ACDQacdq", choice)))
{
while (getchar() != '\n')
continue;
puts("You should input A,C or D to select options,try again");
}
while (getchar() != '\n')
continue;
switch (choice)
{
case 'A':
case 'a':
{
puts("Please add new book titles.");
s_gets(library[count].title, MAXTITL);
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;
break;
}
case 'D':
case 'd':
{
puts("Please input the title of the book you wanna delete "
"from the list.");
s_gets(temp.title, MAXAUTL);
index = 0;
while (strcmp(library[++index].title, temp.title))
continue;
library[index].is_deleted = 1;
break;
}
case 'C':
case 'c':
{
puts("Please input the title of the book you wanna change "
"from the list.");
s_gets(temp.title, MAXAUTL);
index = -1;
while (strcmp(library[++index].title,temp.title))
continue;
puts("Please add new book titles.");
s_gets(library[index].title, MAXTITL);
puts("Now enter the author.");
s_gets(library[index].author, MAXAUTL);
puts("Now enter the value.");
scanf("%f", &library[index].value);
while (getchar() != '\n')
continue;
break;
}
case 'Q':
case 'q':
goto quit;
}
if (count > 0)
{
puts("Here is the list of your books:");
for (index = 0; index < count; index++)
if(library[index].is_deleted==0)
printf("%s by %s:$%.2f\n", library[index].title,
library[index].author, library[index].value);
rewind(pbooks);
fwrite(&library[0], size, count, pbooks);
}
else
puts("No books?Too bad.\n");
}
quit:puts("Bye.\n");
fclose(pbooks);
return 0;
}
char* s_gets(char* st, int n)
{
char* ret_val, * find;
if (ret_val = fgets(st, n, stdin))
if (find = strchr(st, '\n'))
*find = '\0';
else
while (getchar() != '\n')
continue;
return ret_val;
}