// FSeek.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "stdio.h"
#include "string.h"
#include "iostream.h"
#define STU_NUM 100
struct STU
{
int id;
double score;
char name[20];
};
void MakeFile()
{
FILE * fp = fopen("c://stu.dat","wb");
for(int i=0;i<STU_NUM; i++)
{
STU stu;
memset(&stu,0,sizeof(STU));
stu.id =i;
stu.score = i+0.01*i;
strcpy(stu.name,"hello");
fwrite(&stu,sizeof(STU),1,fp);
}
fclose(fp);
}
int GetRecordCount()
{
FILE *fp = fopen("c://stu.dat","rb");
fseek(fp,0,SEEK_END);
int len = ftell(fp);
int nCount = len / sizeof(STU);
printf("文件记录总数为:%d/n",nCount);
fclose(fp);
return nCount;
}
void Read(int nIndex)
{
FILE *fp = fopen("c://stu.dat","rb");
fseek(fp,nIndex * sizeof(STU),SEEK_SET);
STU stu;
memset(&stu,0,sizeof(STU));
fread(&stu,sizeof(STU),1,fp);
printf("记录为:【id::%d - score::%.2f - name::%s】/n",stu.id,stu.score,stu.name);
fclose(fp);
}
int main(int argc, char* argv[])
{
MakeFile();
int nCount = GetRecordCount();
while(nCount > 0)
{
int nIndex;
cout << "/n 输入学号读取对应学生记录,输入 -1 结束:/n";
cin >> nIndex;
if(nIndex <0 )
{
break;
}
if(nIndex > nCount)
{
printf("范围超出/n");
continue;
}
Read(nIndex);
}
return 0;
}