fseek

// 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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值