C++二进制文件读写
简单二进制文件读写,多文件
/*Demo9.1.cpp*/
1 #include <iostream> 2 #include <fstream> 3 #include <string> 4 #include <windows.h> 5 #include "UserList.h" 6 using namespace std; 7 8 int showMain() 9 { 10 system("cls"); 11 cout<<"1.增加"<<endl; 12 cout<<"2.删除"<<endl; 13 cout<<"3.修改"<<endl; 14 cout<<"4.查询"<<endl; 15 cout<<"0.退出"<<endl; 16 cout<<"请选择:"; 17 cin.sync(); 18 int c; 19 cin>>c; 20 return c; 21 } 22 23 void ADD(UserList &L) 24 { 25 cout<<"input:"<<endl; 26 string id,name,password; 27 cin>>id>>name>>password; 28 User u(id,name,password); 29 L.Add(u); 30 } 31 void DEL(UserList &L) 32 {cerr<<"功能未定义"<<endl;Sleep(512);} 33 void REV(UserList &L) 34 {cerr<<"功能未定义"<<endl;Sleep(512);} 35 void SEE(UserList &L) 36 { 37 cout<<"表:"<<endl; 38 for(int i=0;i<L.getN();i++) 39 L.display(i); 40 cout<<endl; 41 system("pause"); 42 } 43 44 int main() 45 { 46 UserList L; 47 // User admin("0","admin","admin"); 48 // L.Add(admin); 49 bool flag=true; 50 while(flag) 51 { 52 switch(showMain()) 53 { 54 case 0:flag=false;break; 55 case 1:ADD(L);break; 56 case 2:DEL(L);break; 57 case 3:REV(L);break; 58 case 4:SEE(L);break; 59 default:break; 60 } 61 } 62 Sleep(256); 63 return 0; 64 }
/*UserList.h*/
1 #include <fstream> 2 #include "User.h" 3 using namespace std; 4 5 class UserList 6 { 7 protected: 8 User *List; 9 int N,nMax; 10 string FileName; 11 public: 12 UserList(/*string Fn=""*/) 13 { 14 List=new User[32]; 15 N=0; 16 nMax=32; 17 // FileName=Fn; 18 FileName="D:\\#\\Users.dat"; 19 readFile(); 20 } 21 // 22 bool readFile() 23 { 24 ifstream fin(FileName.c_str(),ios::binary); 25 if(!fin) 26 return false; 27 fin.seekg(0,ios::end); 28 int FileLen=fin.tellg(),len=sizeof(User); 29 fin.seekg(0,ios::beg); 30 fin.read((char *)List,(N = FileLen<nMax*len?FileLen/len:nMax)*len); 31 fin.close(); 32 /* 33 printf("*%d*",N); 34 for(int i=0;i<N;i++) 35 display(i); 36 cout<<endl; 37 */ 38 return true; 39 } 40 int Add(User u) 41 { 42 if(N<nMax) 43 { 44 List[N]=u; 45 ofstream fout(FileName.c_str(),ios::app|ios::binary); 46 int len=sizeof(User); 47 fout.seekp((N)*len); 48 fout.write((char *)&List[N],len); 49 fout.close(); 50 51 N++; 52 return N-1; 53 }//'else-重分配内存'或'使用vector容器'解决数据溢出 54 return -1; 55 } 56 void idFind(string id) 57 { 58 } 59 void nameFind(string name) 60 { 61 } 62 void display(int i) 63 {cout<<"ID:"<<List[i].id<<endl<<"Name:"<<List[i].name<<endl<<"Password:"<<List[i].password<<endl;} 64 int getN() 65 {return N;} 66 };
/*User.h*/
1 #include <iostream> 2 #include <string> 3 using namespace std; 4 5 class User 6 { 7 friend class UserList; 8 protected: 9 string id; 10 string name; 11 string password; 12 public: 13 User(string id="",string name="",string password=""):id(id),name(name),password(password) 14 {} 15 };
后序慢慢补充
本文来自:[ https://www.cnblogs.com/Leroscox ]
博主:[ MiK ]
——
非商业转载请附原文链接!
商业转载请获得博主许可!