#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;
int dele;
};
int main(void)
{
struct book library[MAXBKS];
int count = 0;
int index, filecount;
FILE * pbooks;
int size = sizeof (struct book);
if ((pbooks = fopen("book.dat", "r+b")) == NULL)
{
fputs("Can't open book.dat 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.dat:");
printf("%s by %s: $%.2f\n",library[count].title,
library[count].author, library[count].value);
count++;
}
filecount = count;
puts("Enter the line number to edit,0 to quit:");
while (count <= MAXBKS && scanf("%d",&count) != EOF
&& count!=0)
{
while (getchar() != '\n')
continue; /* clear input line */
printf("Enter 1 to delete,0 to edit.",count);
scanf("%d",&library[count-1].dele);
while (getchar() != '\n')
continue;
if(library[count-1].dele!=1)
{
printf("edit row %d title.",count);
s_gets(library[count-1].title, MAXAUTL);
printf("edit row %d author.",count);
s_gets(library[count-1].author, MAXAUTL);
printf("edit row %d value.",count);
scanf("%f", &library[count-1].value);
while (getchar() != '\n')
continue;
}
puts("input row number to edit,0 to quit:");
}
rewind(pbooks);
if (count == 0)
{
puts("Here is the list of your books:");
for (index = 0; index < filecount; index++)
{
if(library[index].dele!=1) //删除的不打印出来
{
printf("%s by %s: $%.2f\n",library[index].title,
library[index].author, library[index].value);
}
fwrite(&library[index], size,1,pbooks);
}
}
puts("Bye.\n");
fclose(pbooks);
return 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'); // look for newline
if (find) // if the address is not NULL,
*find = '\0'; // place a null character there
else
while (getchar() != '\n')
continue; // dispose of rest of line
}
return ret_val;
}