输出“stud.dat” :
#include <fstream>
#include "stdlib.h"
#include "stdio.h"
#include "string.h"
#include "io.h"
#include<iostream>
using namespace std;
struct student
{
char name[20];
int num;
int age;
char sex;
};
int main()
{
student stud[3] = { "Li", 1001, 18, 'f', "Fun", 1002, 19, 'm', "Wang", 1004, 17, 'f' };
ofstream outfile("stud.dat", ios::binary);
if (!outfile)
{
cerr << "open error!" << endl;
abort();//退出程序
}
for (int i = 0; i<3; i++)
outfile.write((char*)&stud[i], sizeof(stud[i]));
outfile.close();
cout << sizeof(stud[0].name) << endl;
return 0;
}
读入“stud.dat” :
#include <fstream>
#include "stdlib.h"
#include "stdio.h"
#include "io.h"
#include<iostream>
#include <string>
using namespace std;
struct student
{
char name[20];
int num;
int age;
char sex;
};
int main()
{
student stud[3];
int i;
ifstream infile("stud.dat", ios::binary);
if (!infile)
{
cerr << "open error!" << endl;
abort();
}
for (i = 0; i<3; i++)
infile.read((char*)&stud[i], sizeof(stud[i]));
for (i = 0; i<3; i++)
{
cout << "NO." << i + 1 << endl;
cout << "name:" << stud[i].name << endl;
cout << "num:" << stud[i].num << endl;
cout << "age:" << stud[i].age << endl;
cout << "sex:" << stud[i].sex << endl;
}
infile.close();
return 0;
}