您好,登錄后才能下訂單哦!
// file3.cpp : 定義控制臺應用程序的入口點。 // // #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); //定義文件輸出流 文件不存在時創建文件 //對文件打開錯誤時的操作 if(!outFile) { cout<<"The file open error!"<<endl; return 0; } else //文件正常打開時,進行相應的處理 { Student *s=new Student; cout<<"輸入學生姓名:"; cin>>s->name; cout<<"輸入學生學號:"; cin>>s->num; outFile.write((char*)s,sizeof(Student)); //文件輸出流向文件中寫入student信息 } outFile.close(); //關閉輸出流 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<<"學號:"<<s->num<<endl; } inFile.close(); //關閉輸入流 } void addCustomers(char *identityCard,int number,int isExist) // 添加顧客信息 想總的顧客信息索引表中添加數據 { ifstream inf("botao.dat",ios::in|ios::binary); if(!inf) { cout<<"文件不存在,正在創建……"<<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(); //將緩沖中數據刷如到文件中 } else //如果此顧客已經存在 { 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); //將指針定位到修改信息后的結構體前面 iinFile.read((char*)index,sizeof(Student)); cout<<"姓名:"<<index->name<<endl; cout<<"學號:"<<index->num<<endl; iinFile.close(); break; } index=new Student; } } } //delete index; outFile.close(); } int main() { cout<<"The main .............."<<endl; //addInFile(); //添加結構體 addCustomers("botao1",1,1); //myReadFile(); //讀取結構體 return 0; }
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。