- 论坛徽章:
- 0
|
最近,老师要我们用C语言编写一个存储、查询图书馆书记信息的程序。保存没有问题,但是即使输入一个正确的书目也查询不到。如果将书籍信息全都读取出来,得到的都是乱码。哪位高手指点、纠正一下小弟,不胜感激。先行谢过。程序如下:
#include<stdio.h>
#include<stdlib.h>
struct booklist_info
{
char name[10]; //书籍名称
char number[9]; //书籍书目
char publisher[10]; //书籍出版社
};
typedef struct booklist_info booklist;
void writetofile(booklist *book1);
void readfromfile(booklist *book1);
void getlength(booklist *book1);
void main()
{
booklist *book1,*book2;
char ch;
FILE *fp1;
int length,i,flag = 0;
printf("what do you want to do?\n"
printf("1.please input 'w' if you want to save the information of the book\n"
printf("2.please input 'r' if you want to read the information of the book\n"
scanf("%c",&ch);
fflush(stdin);
switch(ch)
{
case 'w': //保存书籍信息
{
book1 = (booklist *) malloc (sizeof(booklist));
if(book1 == NULL)
{
printf("not enouh memory\n"
getch();
exit(0);
}
do
{
printf("please input the name of the book(0~9)\n"
gets(book1->name);
fflush(stdin);
printf("please input the number of the book(0~\n"
gets(book1->number);
fflush(stdin);
printf("please intput the publisher of the book(0~9)\n"
gets(book1->publisher);
fflush(stdin);
writetofile(book1);
printf("Do you want to continue to save the booklist?Yes(y) No(n)\n"
scanf("%c",&ch);
fflush(stdin);
}while(ch == 'y');
break;
}
case 'r': //读取书籍信息
{
do
{
printf("please input the number of the book which you what to seek.(0~\n"
book2 = (booklist *) malloc (sizeof(booklist));
if(book2 == NULL)
{
printf("not enouh memory\n"
getch();
exit(0);
}
gets(book2->number);
if((fp1 = fopen("d:\\book.dat","rb")) == NULL)
{
printf("can not open the file\n");
getch();
exit(0);
}
for(i =0;i <= 2;i++) //此处循环上限为2,因为只保存了3个书籍信息。
{
fseek(fp1,i*sizeof(struct booklist_info),SEEK_SET);
fread(book1,sizeof(booklist),1,fp1);
if(book1->number == book2->number)
{
flag = 1;
printf("the name of the book:\n");
printf("%s",book1->name);
printf("\nthe number of the book:\n");
printf("%s",book1->number);
printf("\nthe publisher of the book:\n");
printf("%s",book1->publisher);
getch();
}
}
if(flag == 0)
{
printf("can not find the book\n");
getch();
}
printf("Do you want to continue to seek the booklist?Yes(y) No(n)\n");
scanf("%c",&ch);
fflush(stdin);
}while(ch == 'y');
fclose(fp1);
break;
}
}
free(book1);
free(book2);
}
void writetofile(booklist *book1)
{
FILE *fp;
if((fp = fopen("d:\\book.dat","a")) == NULL)
{
printf("can not build the file\n");
getch();
exit(0);
}
fwrite(book1,sizeof(booklist),1,fp);
fclose(fp);
} |
|