从文件随机读入数据1,3,5,写到p指针中,但是p指向内容始终没变
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct student
{
int num;
string name;
};
int main()
{
student stu[5] = { 1000,"wang",1001,"ling",1002,"zhang",1003,"zhao",1004,"cheng" };
fstream file("stu.dat", ios::in | ios::out | ios::binary);
for (int i = 0; i < 5; i++)
{
file.write((char*)&stu[i], sizeof(stu[0]));
}
file.seekg(ios::beg);
void* p;
p= &stu[0];
student* q = &stu[1];
for (int i = 0; i < 5; i=i+2)
{
file.seekg( i * sizeof(stu[0]),ios::beg);
file.read((char*)p, sizeof(stu[0]));
file.read((char*)&stu[i], sizeof(stu[0]));
q = (student*)p;
cout << q->num << '\t' << q->name << endl;
cout << stu[i].num << '\t' << stu[i].name << endl;
}
file.close();
system("pause");
return 0;
}
运行结果
1000 wang
1000 wang
1000 wang
1002 zhang
1000 wang
1004 cheng