{d=SeqDelete(A, s, x); if(d) ofs.write((char*)A, (s-1)*b2); else ofs.write((char*)A,s*b2); break;//处理完最后一个数据块时退出while(1)循环 }} delete [] A; ifs.close(); ofs.close(); remove(fn2); rename("temp", fn2); if(d) return true; else return false; } //从由fn2指针所表示的索引有序文件中 //查找关键字为x.key的索引项并由x带回 template bool InFile::IFSearch(char* fn2, T& x) {ifstream ifs(fn2,ios::in|ios::binary); //以输入方式打开由fn2指针所表示的索引有序文件 if(!ifs) {cerr< ifs.seekg(0,ios::end); int b2=sizeof(T); int n=ifs.tellg()/b2; ifs.seekg(0); int low=0, high=n-1; while(low<=high) { //计算区间中点元素的下标 int mid=(low+high)/2; //从文件中读入区间中点元素并赋给tm T tm; ifs.seekg(mid*b2); ifs.read((char*)&tm,b2); //查找成功后由x带回查找到的索引项并返回真 if(x.key==tm.key) {x=tm; ifs.close(); return true;} //在左子表中继续查找 else if(x.key high=mid-1; //在右子表中继续查找 else low=mid+1;} ifs.close(); return false;}//查找失败返回假 #endif // !defined(AFX_INDEX_H__68B93657_9E7D_4BE5_9259_4780B68E38BD__INCLUDED_)
调用如下 [cpp] #include "stdafx.h" #include #include #include #include #include "Index.h" //索引文件的类实现的测试 void main() {cout<<"运行结果:\n"; //定义保存记录的数组a并初始化 ElemType a[15]={{13,"li"},{18,"liu"},{17,"wphp"},{37,"menrm"}, {8,"ytong"},{22,"zhua"},{24,"push"},{48,"qian"},{34,"tang"}, {57,"shdm"},{55,"kang"},{30,"liuli"},{25,"qiaoh"}, {31,"dukun"},{17,"haiang"}}; //定义保存记录关键字的数组b并初始化 KeyType b[16]={12,18,15,32,6,23,21,48,36,57,45,29,25,38,14,9}; //定义主文件和索引文件的名字,并由字符指针p1和p2所指向 char *p1=".\\HFile1.dat",*p2=".\\HFile1.idx"; int m;//记录个数 InFile myfile; //利用键盘输入操作主文件、索引文件的插入、删除和查找 while(1) { cout< cout<<"1---向主文件插入若干记录"< cout<<"2---从主文件中删除若干记录"< cout<<"3---从主文件中查找若干记录"< cout<<"4---输出主文件fn1"< cout<<"5---输出索引文件fn2"< cout<<"6---结束运行"< char ch; cout<<"请输入你的选择(1-6): ";cin>>ch; switch (ch) {case '1':cout<<"输入待插入记录个数m:"; cin>>m;myfile.MFAppend(p1,p2,a,m);break; case '2':cout<<"输入待删除记录个数m:"; cin>>m;myfile.MFDelete(p1,p2,b,m);break; case '3':cout<<"输入待查找记录个数m:"; cin>>m;myfile.MFSearch(p1,p2,b,m);break; case '4':myfile.PrintMainFile(p1);break; case '5':myfile.PrintIndexFile(p2);break; case '6':return; default:cout<<"输入选择错误,请重输!"< }}}
效果如下
  
|