#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include <ctype.h>
#define MAXTITL 40
#define MAXAUTL 40
#define MAXBKS 20 // 最大图书数量
char *s_gets(char *st, int n);
struct book
{ // 建立book模板
char title[MAXTITL];
char author[MAXAUTL];
float value;
int delete_flag; // 标记0为未删除 1为已删除
}; // 添加删除标记成员
int main(void)
{
int count = 0;
char bookname_delete[MAXTITL];
char choice;
FILE *fr, *fw;
struct book arr[MAXBKS];
fr = fopen("book.dat", "rb");
if (fr == NULL)
{
printf("Failed to open file!\n");
exit(EXIT_FAILURE);
}
while (count < MAXBKS && fread(&arr[count], sizeof(struct book), 1, fr) == 1)
{
if (count == 0)
{
printf("书籍信息如下:\n");
printf("书名 作者 价格\n");
}
if (arr[count].delete_flag == 0)
{
printf("%-16s%-16s%.2f %d\n", arr[count].title, arr[count].author, arr[count].value, arr[count].delete_flag);
count++;
}
}
fclose(fr);
if (count == MAXBKS)
{
printf("书籍已经放满了.");
exit(2);
}
struct book *ptr = &arr[0];
while (1)
{
printf("请问需要删除文件吗?(请输入y或者n):");
int result = scanf(" %c", &choice); // 注意这里加上空格,以清除之前的缓存
if (result == 1)
{
if (choice == 'y' || choice == 'Y')
{
printf("请输入想要删除的书籍:");
scanf("%s", bookname_delete);
while (getchar() != '\n')
continue;
for (int i = 0; i < count; i++)
{
if (strcmp(arr[i].title, bookname_delete) == 0)
{
arr[i].delete_flag = 1;
}
}
}
else if (choice == 'n')
{
break;
}
else
{
printf("请重新输入,请输入y或者n(y代需要,n代表不需要):");
}
}
while (getchar() != '\n')
continue;
}
printf("输入两个回车退出输入\n");
printf("请输入书名:");
count = 0;
int books = 0;
while (count < MAXBKS && s_gets((ptr + count)->title, MAXTITL) != NULL)
{
if ((ptr + count)->title[0] != '\0')
{
printf("现在请输入作者名:");
s_gets((ptr + count)->author, MAXAUTL);
printf("现在请输入价格:");
scanf("%f", &(ptr + count)->value);
(ptr + count)->delete_flag = 0;
while (getchar() != '\n')
continue;
count++;
}
else
{
break;
}
printf("请输入书名:\n");
}
for (int i = 0; i < MAXBKS; i++)
{
if ((ptr + i)->delete_flag == 0)
{
books++;
}
}
if (books == 0)
{
printf("文件中没有书");
exit(1);
}
else
{
for (int i = 0; i < books; i++)
{
if (arr[i].delete_flag == 0)
printf("%-10s的作者是%-10s,价格为%.2f\n", arr[i].title, arr[i].author, arr[i].value);
}
}
fw = fopen("book_new.dat", "wb");
if (fw == NULL)
{
printf("Failed to open file!\n");
exit(EXIT_FAILURE);
}
for (int i = 0; i < count; i++)
{
if (arr[i].delete_flag == 0)
{
fwrite(&arr[i], sizeof(struct book), 1, fw);
}
}
fclose(fw);
remove("book.dat");
rename("book_new.dat", "book.dat");
printf("程序结束.");
return 0;
}
char *s_gets(char *st, int n)
{
char *ret_val; // 存储 fgets 函数的返回值
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; // 返回字符串的起始地址
}