整个添加函数的完整代码:
程序代码:
int Addbook()
{
int i,c;
Book p;
Book list[maxbook];
int j=-1;
fstream iofile;
ifstream infile;
ofstream outfile;
loop:cout<<"请输入需要添加图书名称:";
cin>>p.bname;cout<<endl; //输入书名
do
{
cout<<"请输入图书的五位数编号:";
cin>>p.bid;cout<<endl; //输入书的ID号
}while(p.bid<10000||p.bid>99999); //检查ID号的合法性
cout<<"请输入需要添加图书作者:";
cin>>p.bauthor;cout<<endl; //输入作者
cout<<"请输入添加的图书出版社:";
cin>>p.bpublisher;cout<<endl; //输入出版单位
do
{
cout<<"请输入图书的关键字A-Z:";
cin>>p.bkeyword;cout<<endl; //设置书的关键字
}while(p.bkeyword<65||p.bkeyword>90);
do
{
cout<<"请输入要添加图书的数量:";
cin>>p.bsum;cout<<endl; //输入数的数量
}while(p.bsum<=0);
do
{
cout<<"输入数字1确认此书信息:";
cin>>p.flag;cout<<endl;
}while(p.flag!=1); //确认输入数的信息
iofile.open("booksum.txt",ios::in|ios::binary); //以输入方式打开当前书目数量文件
if(!iofile)
{
cerr<<"打开失败"<<endl;
iofile.open("booksum.txt",ios::out); //file doesn't exist,create a new one
booksum=0;
}
else
{
iofile.close();
iofile.open("booksum.txt",ios::in|ios::binary);
iofile>>booksum;
}
iofile.close();
c=booksum;
if(c==0)
{
cout<<"当前书库有"<<c<<"本图书"<<endl;
cout<<"你所添加的书目信息为:"<<endl;
cout<<"图书名称:"<<p.bname<<endl;
cout<<"图书编号:"<<p.bid<<endl;
cout<<"图书作者:"<<p.bauthor<<endl;
cout<<"图书出版社:"<<p.bpublisher<<endl;
cout<<"图书数量:"<<p.bsum<<endl;
iofile.open("book.txt",ios::in); //以输入,输出方式打开book.txt
if(!iofile)
{
iofile.open("book.txt",ios::out); //file doesn't exist,create a new one
iofile.close();
iofile.open ("book.txt",ios::in|ios::out|ios::binary);
}
else
{ iofile.close();
iofile.open("book.txt",ios::in|ios::out|ios::binary);
}
iofile.seekp(0,ios::beg);
iofile.write((char*)&p,sizeof(p));
iofile.close();
outfile.open("booksum.txt",ios::out);
booksum=booksum+1;
outfile<<booksum;
outfile.close();
}
else
{ cout<<"当前书库有"<<c<<"本图书"<<endl;
iofile.open("book.txt",ios::in|ios::out|ios::binary);
for(i=0;i<c;i++)
{iofile.seekg(i*sizeof(list[i]),ios::beg);
iofile.read((char*)&list[i],sizeof(list[i]));
if(p.bid==list[i].bid)
{j=i;
break;}
}
iofile.close();
if(j==-1)
{
cout<<"你所添加的书目信息为:"<<endl;
cout<<"图书名称:"<<p.bname<<endl;
cout<<"图书编号:"<<p.bid<<endl;
cout<<"图书作者:"<<p.bauthor<<endl;
cout<<"图书出版社:"<<p.bpublisher<<endl;
cout<<"图书数量:"<<p.bsum<<endl;
iofile.open("book.txt",ios::in|ios::out|ios::binary);
iofile.seekp(0,ios::end);
iofile.write((char*)&p,sizeof(p));
iofile.close();
outfile.open("booksum.txt",ios::out);
booksum=booksum+1;
outfile<<booksum;
outfile.close();
}
else if(j>=0)
{ cout<<"你所输入图书编号已存在,该书目将合并入此记录"<<endl;
Book book;
list[j].bsum=list[j].bsum+p.bsum;
iofile.open("book.txt",ios::in|ios::out|ios::binary);
iofile.seekg(j*sizeof(book),ios::beg);
iofile.read((char*)&book,sizeof(book));
book.bsum=list[j].bsum;
iofile.seekp(j*sizeof(book),ios::beg);
iofile.write((char*)&book,sizeof(book));
iofile.close();
}
else cerr<<"出现错误"<<endl;
}