C++文件读写之对象的读写(四)

2014-11-24 12:30:27 · 作者: · 浏览: 1
00 }
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!"<
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 }
复制代码
复制代码
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!"<
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 }