#define _CRT_SECURE_NO_WARNINGS
#include
#include
#include
#include
using namespace std;
class Worker
{
public:
int num;
char name[20];
int age;
int wage;
};
Worker work[5] = { 12, "Zhang", 22, 10000, 4, "Li", 23, 1000, 2, "Fan", 52, 100, 8, "Wu", 24, 10, 6, "Ha", 28, 12000 };
void swap(Worker worker[], int i, int j)
{
int temp1, temp2, temp3;
char temp4[20];
temp1 = worker[i].num;
temp2 = worker[i].age;
temp3 = worker[i].wage;
strcpy(temp4, worker[i].name);
worker[i].num = worker[j].num;
worker[i].age = worker[j].age;
worker[i].wage = worker[j].wage;
strcpy(worker[i].name, worker[j].name);
worker[j].num = temp1;
worker[j].age = temp2;
worker[j].wage = temp3;
strcpy(worker[j].name, temp4);
}
void fun1() //将5个工人数据写入到文件,fun1函数正常
{
ofstream outfile("work.txt", ios::out);
if (!outfile)
{
cerr << "open error!" << endl;
abort();
}
outfile.close();
fstream iofile("work.txt", ios::out | ios::in | ios::binary);
if (!iofile)
{
cerr << "open error!" << endl;
abort();
}
for (int i = 0; i < 4; i++)
{
for (int j = i; j < 4; j++)
{
if (work[i].num > work[j + 1].num)
{
swap(work, i, j);
}
}
}
for (int i = 0; i < 5; i++)
{
iofile.write((char )&work[i], sizeof(work[i]));
iofile.seekg(i*sizeof(work[i]), ios::beg);
iofile.read((char *)&work[i], sizeof(work[i]));
cout << work[i].num << " " << work[i].name << " " << work[i].age << " " << work[i].wage << endl;
}
iofile.close();
}
void fun2()//输出乱码,为什么
{
ofstream outfile("work.txt", ios::app|ios::binary);
if (!outfile)
{
cerr << "open error!" << endl;
abort();
}
Worker worker[2] = { 101, "Lin", 72, 10800, 104, "Ka", 29, 10020 };
for (int i = 0; i < 2; i++)
{
outfile.write((char)&worker[i], sizeof(worker[i]));
}
outfile.close();
Worker all_work[7];
ifstream infile("work.txt", ios::in|ios::binary);
if (!infile)
{
cerr << "open error!" << endl;
abort();
}
for (int i = 0; i < 7; i++)
{
infile.seekg(i*sizeof(all_work[i]), ios::beg);
infile.read((char*)&all_work[i], sizeof(all_work[i]));
cout << all_work[i].num << " " << all_work[i].name << " " << all_work[i].age << " " << all_work[i].wage << endl;
}
infile.close();
}
void main()
{
fun1();
fun2();
system("pause");
}