demo_5_file_dat_3.cpp
来自「对于一个初涉VC++的人来书」· C++ 代码 · 共 90 行
CPP
90 行
//***************************************************
// 随机访问二进制数据文件
//***************************************************
# include <fstream.h>
# include <string.h>
# include <stdlib.h>
struct student
{
int num;
char name[20];
float score;
};
int main()
{
int i;
student stud[6]={1001,"Li",85,1002,"Fei",97.5,1004,"Wang",54,
1006,"Tan",76.5,1010,"Ling",96,1012,"Zheng",100};
fstream file("stud.dat",ios::in|ios::out|ios::binary);
if(!file)
{
cerr<<"open error!"<<endl;
exit(1);
}
for(i=0;i<6;i++)
{
cout<<stud[i].num<<" "<<stud[i].name<<" "<<stud[i].score<<endl;
file.write((char *)&stud[i],sizeof(stud[i]));
}
cout<<endl;
student stud_temp[6];
for(i=0;i<6;i=i+2)
{
file.seekg(i*sizeof(stud[i]),ios::beg); //文件读指针移动
// cout<<file.tellg()<<endl; //返回文件读指针当前位置
file.read((char *)&stud_temp[i/2],sizeof(stud_temp[i]));
cout<<stud_temp[i/2].num<<" "<<stud_temp[i/2].name<<" "<<stud_temp[i/2].score<<endl;
}
cout<<endl;
stud[2].num=1012;
strcpy(stud[2].name,"Wu");
stud[2].score=60;
file.seekp(2*sizeof(stud[0]),ios::beg);
// cout<<file.tellp()<<endl; //返回文件写指针当前位置
file.write((char *)&stud[2],sizeof(stud[2]));
file.seekg(0,ios::beg); //文件读指针移动
// cout<<file.tellg()<<endl; //返回文件读指针当前位置
for(i=0;i<6;i++)
{
file.read((char *)&stud[i],sizeof(stud[i]));
cout<<stud[i].num<<" "<<stud[i].name<<" "<<stud[i].score<<endl;
}
file.close();
return 0;
}
/*
1001 Li 85
1002 Fei 97.5
1004 Wang 54
1006 Tan 76.5
1010 Ling 96
1012 Zheng 100
1001 Li 85
1004 Wang 54
1010 Ling 96
1001 Li 85
1002 Fei 97.5
1012 Wu 60
1006 Tan 76.5
1010 Ling 96
1012 Zheng 100
*/
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?