首先是对象的建立,包括姓名,学号,成绩,学分,等
如下:
这里面包括两个子对象,
复制代码
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 };
复制代码
然后主要还是文件读写。文件读写包括三个类,其中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();
定义一个全局函数用于获取文件中对象的个数,
复制代码
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!"<
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 }
复制代码
这里的文件读写关键是在read函数,read函数会读取数据一直到文件结束
1 basic_istream& read(
2 char_type *_Str, //这里是要保存的对象数组的地址
3 streamsize _Count//这里是对象的大小
4 );
因为数据是以二进制保存到文件中的,所以我们不用关心数据的格式,我们知道怎么读取数据就行了。向文件中写入整个对象的好处是将来可以整个读取出来进行操作,不必去考虑细节。
写入文件和这个类似
复制代码
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();
复制代码
以app方式打开文件进行添加,文件内部的位置指针会自动移动移动到文件末尾,直接添加文件到最后。
当对文件进行输出时
复制代码
1 fstream infile("e:\\student.txt",ios::in | ios::binary);
2 if (!infile)
3 {
4 cout<<"open file error!"<
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();
复制代码
还有一些排序的简单实现在下面的代码中
整个程序代码在这里
复制代码
1 #include
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 i