您好,登錄后才能下訂單哦!
// file3.cpp : 定義控制臺應(yīng)用程序的入口點。 // // #include "stdafx.h" #include <fstream> #include <iostream> using namespace std; struct Student{ char name[20]; int num; }; int addInFile() { ofstream outFile("botao.dat",ios::out|ios::binary); //定義文件輸出流 文件不存在時創(chuàng)建文件 //對文件打開錯誤時的操作 if(!outFile) { cout<<"The file open error!"<<endl; return 0; } else //文件正常打開時,進(jìn)行相應(yīng)的處理 { Student *s=new Student; cout<<"輸入學(xué)生姓名:"; cin>>s->name; cout<<"輸入學(xué)生學(xué)號:"; cin>>s->num; outFile.write((char*)s,sizeof(Student)); //文件輸出流向文件中寫入student信息 } outFile.close(); //關(guān)閉輸出流 return 1; } int myReadFile() { ifstream inFile("botao.dat",ios::in|ios::binary); //文件輸入流 將文件中的student信息讀出到屏幕上 //對文件打開錯誤時的操作 if(!inFile) { cout<<"The inFile open error!"<<endl; return 0; } else { Student *s=new Student; inFile.read((char*)s,sizeof(Student)); cout<<"姓名:"<<s->name<<endl; cout<<"學(xué)號:"<<s->num<<endl; } inFile.close(); //關(guān)閉輸入流 } void addCustomers(char *identityCard,int number,int isExist) // 添加顧客信息 想總的顧客信息索引表中添加數(shù)據(jù) { ifstream inf("botao.dat",ios::in|ios::binary); if(!inf) { cout<<"文件不存在,正在創(chuàng)建……"<<endl; ofstream outf("botao.dat",ios::out|ios::binary); outf.close(); } inf.close(); fstream outFile("botao.dat",ios::app|ios::in|ios::binary); Student *index=new Student; if(!outFile) { cout<<"Open Error!"<<endl; //exit(1); } else { if(isExist==0) //如果此顧客還沒有在此航空公司買過票 { outFile.seekp(ios::end); //文件指針重新定位 index->num=0; strcpy(index->name,identityCard); index->num=number; outFile.write((char*)index,sizeof(Student)); //*****將信息寫入到文件中 cout<<"index->name:"<<index->name<<endl; cout<<"index ->num:"<<index->num<<endl; //outFile.flush(); //將緩沖中數(shù)據(jù)刷如到文件中 } else //如果此顧客已經(jīng)存在 { while(outFile.read((char*)index,sizeof(Student))) // { if(strcmp(identityCard,index->name)==0) { cout<<"指針移動前:--------"<<outFile.tellg()<<endl; outFile.seekg(-(long)sizeof(Student),ios::cur); cout<<"指針移動后:--------"<<outFile.tellg()<<endl; index->num=0; strcpy(index->name,identityCard); index->num=number; cout<<"index->name:"<<index->name<<endl; cout<<"index->num:"<<index->num<<endl; if(outFile.write((char*)index,sizeof(Student))) //*****將修改后信息寫入到文件中 cout<<"cheng gong ________________________"<<endl; //myReadFile(); ifstream iinFile("botao.dat",ios::in|ios::binary); //Student *s=new Student; iinFile.seekg(-(long)sizeof(Student),ios::cur); //將指針定位到修改信息后的結(jié)構(gòu)體前面 iinFile.read((char*)index,sizeof(Student)); cout<<"姓名:"<<index->name<<endl; cout<<"學(xué)號:"<<index->num<<endl; iinFile.close(); break; } index=new Student; } } } //delete index; outFile.close(); } int main() { cout<<"The main .............."<<endl; //addInFile(); //添加結(jié)構(gòu)體 addCustomers("botao1",1,1); //myReadFile(); //讀取結(jié)構(gòu)體 return 0; }
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。