码迷,mamicode.com
首页 > 编程语言 > 详细

C++文件读写之对象的读写

时间:2014-05-10 01:53:51      阅读:436      评论:0      收藏:0      [点我收藏+]

标签:style   blog   class   code   java   tar   

   这里以一个简单的学生信息管理系统为例。

  首先是对象的建立,包括姓名,学号,成绩,学分,等

  如下:

  这里面包括两个子对象,

bubuko.com,布布扣
 1 class Student
 2 {
 3 public:
 4     Student() :score(), birthday(){}//对子对象进行初始化
 5     ~Student(){}
 6     void InputInfo();
 7     void OutPutInfo();
 8     void ShowInfo();
 9     bool CreditManage();
10 
11     char *getNum(){ return num; }
12     char *getName(){ return name; }
13     bool getSex(){ return sex; }
14     float GetCredit(){ return credit; }
15     void swapStudent(Student &stu);
16 private:
17     char  num[10];
18     char name[20];
19     bool sex;
20     Score score;//子对象
21     Birthday birthday;//子对象
22     float credit;
23     bool isChanged;
24 };
bubuko.com,布布扣

  然后主要还是文件读写。文件读写包括三个类,其中ifstream和ofstrean从fstream派生而来,可以在创建对象的时候直接初始化,这样比较方便。也可以使用open函数打开文件

    (1) ifstream类,它是从istream类派生的。用来支持从磁盘文件的输入。

    (2) ofstream类,它是从ostream类派生的。用来支持向磁盘文件的输出。

    (3) fstream类,它是从iostream类派生的。用来支持对磁盘文件的输入输出。

  其中的文件读写的关键函数是read和write,这两个函数可以读写固定长度的数据

      istream& read(char *buffer,int len);

      ostream& write(const char * buffer,int len);

  文件操作完毕一定要关闭文件,只需调用close()就行。

  如file.close();

  定义一个全局函数用于获取文件中对象的个数,

bubuko.com,布布扣
 1 int GetNumberFromFile()
 2 {
 3     int count = 0;//对象个数,即学生人数
 4     fstream infile("e:\\student.txt",ios::in | ios::binary);//以读方式打开文件
 5     if (!infile)
 6     {
 7         cout<<"open file error!"<<endl;
 8         getchar();
 9         exit(0);
10     }
11     Student stu;
12     while (infile.read((char*)&stu,sizeof(stu)))//强制类型转换为(char*),
13     {
14         count++;
15     }
16     infile.close();
17     return count;
18 }
bubuko.com,布布扣

  这里的文件读写关键是在read函数,read函数会读取数据一直到文件结束

1 basic_istream<Elem, Tr>& read(
2     char_type *_Str, //这里是要保存的对象数组的地址
3     streamsize _Count//这里是对象的大小
4 );

  因为数据是以二进制保存到文件中的,所以我们不用关心数据的格式,我们知道怎么读取数据就行了。向文件中写入整个对象的好处是将来可以整个读取出来进行操作,不必去考虑细节。

  写入文件和这个类似

bubuko.com,布布扣
1             Student stu1;
2             stu1.InputInfo();
3             fstream outfile("e:\\student.txt", ios::app | ios::binary);//这里以app方式打开文件进行添加
4             if (!outfile)
5             {
6                 cerr << "open file error!";
7             }
8             outfile.write((char*)&stu1, sizeof(stu1));
9             outfile.close();
bubuko.com,布布扣
以app方式打开文件进行添加,文件内部的位置指针会自动移动移动到文件末尾,直接添加文件到最后。

  当对文件进行输出时

bubuko.com,布布扣
 1             fstream infile("e:\\student.txt",ios::in | ios::binary);
 2             if (!infile)
 3             {
 4                 cout<<"open file error!"<<endl;
 5                 getchar();
 6                 //exit(0);
 7             }
 8             int len = 0;
 9             len = GetNumberFromFile();
10             if (len == 0)
11             {
12                 cout << "no data!" << endl;
13                 ch = 0;
14                 break;
15             }
16             Student *stu = new Student[len];//动态申请地址,因为这个数组大小是在运行过程中才能知道的
17             cout << "number\tname\tsex\tyear-month-day\tcredit" << endl;            
18             for (int i = 0; i < len;i++)
19             {
20                 infile.read((char*)&stu[i], sizeof(stu[i]));
21                 stu[i].OutPutInfo();
22             }
23             delete []stu;
24             infile.close();
bubuko.com,布布扣

  

 还有一些排序的简单实现在下面的代码中

整个程序代码在这里

bubuko.com,布布扣
  1 #include <iostream>
  2 #include "string"
  3 using namespace std;
  4 
  5 class Student;
  6 bool SortByCondition(Student stu[],const int &len,const char &conditon);//排序
  7 void SaveToFile(Student stu[],int num);
  8 void ReadFromFile(Student stu[],int num);
  9 int GetNumberFromFile();
 10 char Menu();
 11 char SortMenu();
 12 
 13 class Score
 14 {
 15 public:
 16     Score(){ english = 0, math = 0; computer = 0; }
 17     Score(float eng, float mat, float com) :english(eng), math(mat), computer(com){}
 18     void InputScore()
 19     {
 20         cout << "enter english  score:";
 21         cin>> english;
 22         cout << "enter math     score:";
 23         cin >> math;
 24         cout << "enter computer score:";
 25         cin >> computer;
 26     }
 27     void outputScore()
 28     {
 29         cout << english << "\t" << math << "\t" << computer << "\t";
 30     }
 31     float ScoreSum()
 32     {
 33         return (math + english + computer);
 34     }
 35     void swapScore(Score &scor)//对象交换数据
 36     {
 37         float ftmp = english;
 38         english = scor.english;
 39         scor.english = ftmp;
 40 
 41         ftmp = math;
 42         math = scor.math;
 43         scor.math = ftmp;
 44         
 45         ftmp = computer;
 46         computer = scor.computer;
 47         scor.computer = ftmp;
 48     }
 49 private:
 50     float english;
 51     float math;
 52     float computer;
 53 };
 54 
 55 class Birthday
 56 {
 57 public:
 58     Birthday(){ year = 0; month = 0; day = 0; }
 59     Birthday(int ye, int mon, int da) :year(ye), month(mon), day(da){}
 60     void inputBirthday()
 61     {
 62         cout << "enter birthday like \"2014 05 01\":" << endl;
 63         cin >> year >> month >> day;
 64     }
 65     void outputBirthday()
 66     {
 67         cout << year << "\-" << month << "\-" << day << "\t";
 68     }
 69     void swapBirthday(Birthday &bir)//对象交换数据
 70     {
 71         int itmp = year;
 72         year = bir.year;
 73         bir.year = itmp;
 74 
 75         itmp = month;
 76         month = bir.month;
 77         bir.month = itmp;
 78 
 79         itmp = day;
 80         day = bir.day;
 81         bir.day = itmp;
 82     }
 83 private:
 84     int year;
 85     int month;
 86     int day;
 87 };
 88 
 89 
 90 class Student
 91 {
 92 public:
 93     Student() :score(), birthday(){}
 94     ~Student(){}
 95     void InputInfo();
 96     void OutPutInfo();
 97     void ShowInfo();
 98     bool CreditManage();
 99 
100     char *getNum(){ return num; }
101     char *getName(){ return name; }
102     bool getSex(){ return sex; }
103     float GetCredit(){ return credit; }
104     void swapStudent(Student &stu);//对象交换数据
105 private:
106     char  num[10];
107     char name[20];
108     bool sex;
109     Score score;
110     Birthday birthday;
111     float credit;
112     bool isChanged;
113 };
student.h

 

bubuko.com,布布扣
  1 #include "student.h"
  2 #include "iostream"
  3 #include "fstream"
  4 using namespace std;
  5 
  6 
  7 void Student::InputInfo()
  8 {
  9     cout << "enter number(字符串)";
 10     cin >> num;
 11     cout << "enter name(字符串)";
 12     cin >> name;
 13     cout << "enter sex(0表示女,1表示男)";
 14     cin >> sex;
 15     score.InputScore();
 16     birthday.inputBirthday();
 17     credit = score.ScoreSum() / 10;//计算得出学分
 18 }
 19 
 20 void Student::OutPutInfo()
 21 {
 22     cout << num << "\t" << name << "\t" << sex << "\t";
 23     //score.outputScore();
 24     birthday.outputBirthday();
 25     cout << credit << endl;
 26 }
 27 
 28 char Menu()
 29 {
 30     //system("cls");
 31     cout << "******************************************" << endl;
 32     cout << "***welcome to student management system***" << endl;
 33     cout << "******************************************" << endl;
 34     cout << "please choose the number below:" << endl;
 35     cout << "1--成绩录入" << endl;
 36     cout << "2--成绩显示" << endl;
 37     cout << "3--排序管理" << endl;
 38     cout << "4--学分管理" << endl;
 39     cout << "0--退出" << endl;
 40     char ch = getchar();
 41     return ch;
 42 }
 43 
 44 void Student::swapStudent(Student &stu)
 45 {
 46     char tmp[10];
 47     strcpy_s(tmp, num);
 48     strcpy_s(num, stu.num);
 49     strcpy_s(stu.num, tmp);
 50 
 51     char nam[20];
 52     strcpy_s(nam, name);
 53     strcpy_s(name, stu.name);
 54     strcpy_s(stu.name, nam);
 55 
 56     bool btmp = sex;
 57     sex = stu.sex;
 58     stu.sex = btmp;
 59 
 60     score.swapScore(stu.score);
 61     birthday.swapBirthday(stu.birthday);
 62 
 63     float ftmp = credit;
 64     credit = stu.credit;
 65     stu.credit = ftmp;
 66 
 67     btmp = isChanged;
 68     isChanged = stu.isChanged;
 69     stu.isChanged = btmp;
 70 
 71 }
 72 
 73 char SortMenu()
 74 {
 75     cout << "选择要进行排序的方式:";
 76     cout << "1--学号" << endl;
 77     cout << "2--姓名" << endl;
 78     cout << "3--性别" << endl;
 79     cout << "4--学分" << endl;
 80     cout << "5--返回上一级" << endl;
 81     getchar();
 82     char ch = getchar();
 83     return ch;
 84 }
 85 
 86 bool SortByCondition(Student stu[], const int &len, const char &conditon)//排序
 87 {
 88     char tmp = conditon;
 89     int length = len;
 90     switch (tmp)
 91     {
 92     case 1://学号
 93     {
 94         for (int i = 0; i < length; i++)
 95         {
 96             for (int j = 0; j < length-i-1; j++)
 97             {
 98                 if (strcmp((stu[j].getNum()), stu[j + 1].getNum()) > 0)
 99                 //if (stu[j].getName().compare(stu[j+1].getName()) > 0)
100                 {
101                     //compare(stu[j].getName(),stu[j+1].getName());
102                     //stu[j].getName().compare(stu[j+1].getName());
103                     stu[j].swapStudent(stu[j + 1]);
104                 }
105             }
106         }
107         cout << "学号降序排列" << endl;
108         for (int i = 0; i < length; i++)
109         {
110             stu[i].OutPutInfo();
111 //             if (i % 10 == 0)
112 //             {
113 //                 cout << "按下任意键继续显示" << endl;
114 //                 getchar();
115 //             }
116         }
117         getchar();
118     }
119         break;
120     case 2://姓名
121     {
122         for (int i = 0; i < length; i++)
123         {
124             for (int j = 0; j < length - i - 1; j++)
125             {
126                 if (strcmp(stu[j].getName(), stu[j + 1].getName()) < 0)
127                 //if (stu[j].getNum().compare(stu[j+1].getNum()) > 0)
128                 {
129                     stu[j].swapStudent(stu[j + 1]);
130                 }
131             }
132         }
133         cout << "姓名降序排列" << endl;
134 
135         for (int i = 0; i < length; i++)
136         {
137             stu[i].OutPutInfo();
138 //             if (i % 10 == 0)
139 //             {
140 //                 cout << "按下任意键继续显示" << endl;
141 //                 getchar();
142 //             }
143         }
144         getchar();
145     }
146         break;
147     case 3://性别
148     {
149         for (int i = 0; i < length; i++)
150         {
151             for (int j = 0; j < length - i - 1; j++)
152             {
153                 if (stu[j].getSex() < stu[j + 1].getSex())
154                 {
155                     stu[j].swapStudent(stu[j + 1]);
156                 }
157             }
158         }
159             cout << "性别降序排列" << endl;
160         for (int i = 0; i < length; i++)
161         {
162             stu[i].OutPutInfo();
163 //             if (i % 10 == 0)
164 //             {
165 //                 cout << "按下任意键继续显示" << endl;
166 //                 getchar();
167 //             }
168         }
169         getchar();
170     }
171         break;
172 
173     case 4://学分
174     {
175         for (int i = 0; i < length; i++)
176         {
177             for (int j = 0; j < length - i - 1; j++)
178             {
179                 if (stu[j].GetCredit() < stu[j + 1].GetCredit())
180                 {
181                     stu[j].swapStudent(stu[j + 1]);
182                 }
183             }
184         }
185         cout << "学分降序排列" << endl;
186         for (int i = 0; i < length; i++)
187         {
188             stu[i].OutPutInfo();
189 //             if (i % 10 == 0)
190 //             {
191 //                 cout << "按下任意键继续显示" << endl;
192 //                 getchar();
193 //             }
194         }
195         getchar();
196     }
197         break;
198     default:
199         break;
200     }
201     return true;
202 }
203 
204 int GetNumberFromFile()
205 {
206     int count = 0;//对象个数,即学生人数
207     fstream infile("e:\\student.txt",ios::in | ios::binary);
208     if (!infile)
209     {
210         cout<<"open file error!"<<endl;
211         getchar();
212         exit(0);
213     }
214     Student stu;
215     while (infile.read((char*)&stu,sizeof(stu)))
216     {
217         count++;
218     }
219     infile.close();
220     return count;
221 }
student.cpp

 

bubuko.com,布布扣
  1 #include "student.h"
  2 #include "fstream"
  3 #include "string"
  4 
  5 int main()
  6 {

  7     char ch = Menu();
  8     int  quit = 1;
  9     while (quit)
 10     {
 11         switch (ch)
 12         {
 13         case 1://成绩录入
 14         {
 15             Student stu1;
 16             stu1.InputInfo();
 17             fstream outfile("e:\\student.txt", ios::app | ios::binary);
 18             if (!outfile)
 19             {
 20                 cerr << "open file error!";
 21             }
 22             outfile.write((char*)&stu1, sizeof(stu1));
 23             outfile.close();
 24 
 25             ch = 0;
 26             getchar();
 27         }
 28             break;
 29         case 2://成绩显示
 30         {
 31             fstream infile("e:\\student.txt",ios::in | ios::binary);
 32             if (!infile)
 33             {
 34                 cout<<"open file error!"<<endl;
 35                 getchar();
 36                 //exit(0);
 37             }
 38             int len = 0;
 39             len = GetNumberFromFile();
 40             if (len == 0)
 41             {
 42                 cout << "no data!" << endl;
 43                 ch = 0;
 44                 break;
 45             }
 46             Student *stu = new Student[len];
 47             cout << "number\tname\tsex\tyear-month-day\tcredit" << endl;            
 48             for (int i = 0; i < len;i++)
 49             {
 50                 infile.read((char*)&stu[i], sizeof(stu[i]));
 51                 stu[i].OutPutInfo();
 52             }
 53             delete []stu;
 54             infile.close();
 55             ch = 0;
 56             getchar();
 57         }
 58             break;
 59         case 3://排序管理
 60         {
 61             char condtion = SortMenu();
 62             fstream file("e:\\student.txt", ios::in | ios::binary);
 63             if (!file)
 64             {
 65                 cerr << "open file error!";
 66             }
 67             int len = GetNumberFromFile();
 68             Student *stu = new Student[len];
 69             for (int i = 0; i < len;i++)
 70             {
 71                 file.read((char *)&stu[i], sizeof(stu[i]));
 72             }
 73         
 74             file.close();
 75             SortByCondition(stu,len, condtion);
 76 
 77 
 78             delete []stu;
 79             getchar();
 80         }
 81             break;
 82 
 83         case 4://学分管理
 84         {
 85 
 86         }
 87             break;
 88 
 89         case 0:
 90         {
 91             quit = 0;
 92             exit(0);
 93             ch = 0;//quit switch
 94         }
 95             break;
 96         default:
 97             //ch = ‘0‘;
 98             break;
 99         }
100         //getchar();
101 
102         ch = Menu();
103     }
104     system("pause");
105     return 0;
106 }
main.cpp

 

C++文件读写之对象的读写,布布扣,bubuko.com

C++文件读写之对象的读写

标签:style   blog   class   code   java   tar   

原文地址:http://www.cnblogs.com/songliquan/p/3708137.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!