C++程序设计 (第三版) 谭浩强 例13.14 例13.15
例13.14 将一批数据以二进制形式存放在磁盘文件中。
例13.15 将刚才以二进制形式存放在磁盘文件中的数据读入内存并在显示器上显示。
IDE工具:VS2010
Note: 使用不同的IDE工具可能有部分差异。
代码块:
说明:文件f1.txt,f2.txt都在程序源文件同目录下。
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;
const int N = 3;
typedef struct Student{
int num;
string name;
int age;
char gender;
}Student;
void initialStu(Student **stu, int n){
*stu = new Student[n];
}
void inputStu(Student *stu, int n){
cout<<"Enter "<<n<<" Student Info:"<<endl;
for(int i = 0; i < n; i++){
cout<<"Enter No."<<i + 1<<" Student Number(100 ~ 999): ";
cin>>stu[i].num;
while(stu[i].num < 100 || stu[i].num > 999){
cout<<"Number Error! Retry!\nEnter No."<<i + 1<<" Student Number(100 ~ 999): ";
cin>>stu[i].num;
}
fflush(stdin);
cout<<"Enter No."<<i + 1<<" Student Name: ";
getline(cin, stu[i].name);
cout<<"Enter No."<<i + 1<<" Student Age(18 ~ 30): ";
cin>>stu[i].age;
while(stu[i].age < 18 || stu[i].age > 30){
cout<<"Age Error! Retry!\nEnter No."<<i + 1<<" Student Age(18 ~ 30): ";
cin>>stu[i].age;
}
cout<<"Enter No."<<i + 1<<" Student Gender(M or F): ";
cin>>stu[i].gender;
while(stu[i].gender != 'M' && stu[i].gender != 'F'){
cout<<"Gender Error! Retry!\nEnter No."<<i + 1<<" Student Gender(M or F): ";
cin>>stu[i].gender;
}
cout<<endl;
}
cout<<endl;
}
void freeStu(Student **stu){
delete []*stu;
}
void inputFile(char *name, Student *stu, int n){
ofstream outfile(name, ios::binary);
if(!outfile){
cerr<<"Open File "<<name<<" Error!"<<endl;
system("pause");
exit(0);
}
for(int i = 0; i < n; i++){
outfile.write((char*)&stu[i], sizeof(Student));
}
outfile.close();
}
void outputFile(char *name, Student *stu, int n){
ifstream infile(name, ios::binary);
if(!infile){
cerr<<"Open File "<<name<<" Error!"<<endl;
system("pause");
exit(0);
}
for(int i = 0; i < n; i++){
infile.read((char*)&stu[i], sizeof(Student));
}
infile.close();
cout<<"Student Info:"<<endl;
for(int i = 0; i < n; i++){
cout<<setiosflags(ios::left);
cout<<"Number: "<<setw(3)<<stu[i].num<<" Name: "<<setw(10)<<stu[i].name
<<" Age: "<<setw(2)<<stu[i].age<<" Gender: "<<setw(1)<<stu[i].gender<<endl;
}
cout<<endl;
}
int main(){
Student *stu = NULL;
initialStu(&stu, N);
inputStu(stu, N);
inputFile("f1.txt", stu, N);
outputFile("f1.txt", stu, N);
freeStu(&stu);
system("pause");
return 0;
}