#include<iostream>
#include<fstream>
using namespace std;
struct number
{
char name[20];
int age;
};
int main()
{
number a[] = { {"张三",12},{"李四",15} };
ofstream outfile;
outfile.open("a.txt", ios::out);
if (!outfile)
{
cerr << "打开文件失败" << endl;
exit(1);
}
int nSize = sizeof(a) / sizeof(number);
for (int i = 0; i < nSize; i++)
{
outfile.write((char*)&a[i], sizeof(number));
}
outfile.close();
ifstream infile;
infile.open("a.txt", ios::in);
if (!infile)
{
cerr << "文件打开失败" << endl;
exit(1);
}
number *b = new number[nSize];
for (int i = 0; i < nSize; i++) {
infile.read((char*)(number*)&b[i], sizeof(number));
printf("%s, %d\n", b[i].name, b[i].age);
}
delete[]b;
infile.close();
}
52论坛的帖子,结构体保存到文件中的,读取文件中的结构体。
于 2021-07-08 16:29:03 首次发布