/**
* 实验题目:
* 实现索引文件建立和查找算法
* 实验目的:
* 掌握索引文件的基本操作及其算法设计
* 实验内容:
* 编写程序,建立表12.1中学生成绩记录对应的主文件data.dat,
* 要求完成以下功能:
* 1、输出主文件中的学生记录
* 2、建立与主文件相对应的索引文件,其中每个记录由两个字段组成:
* 学号no及该学生记录在数据文件中的相应位置offset。索引文件中的
* 记录按学号no升序排列。
* 3、输出索引文件全部记录
* 4、根据用户输入的学号,在索引文件中采用折半查找法找到对应记录
* 号,再通过主文件输出记录。
*/
#include <stdio.h>
#define MAX_REC 100 // 最多的记录个数
typedef struct index
{
int no; // 学号
long offset; // 主文件中的记录号
}index; // 索引文件类型
/*-------------设计学生记录类型--------------*/
typedef struct
{
int no; // 学号
char name[10]; // 姓名
int age; // 年龄
char sex[3]; // 性别
int chinese_deg; // 语文成绩
int math_deg; // 数学成绩
int english_deg; // 英语成绩
}stud_type;
/*-------------将st数组中的学生记录写入到二进制文件stud.dat文件中--------------*/
// 由数组st中的n个学生成绩记录建立主文件stud.dat
static void write_file(int n)
{
int i;
FILE *fp;
stud_type st[] = {
{1, "陈华", 20, "男", 78, 99, 84},
{5, "张明", 21, "男", 76, 89, 88},
{8, "王英", 22, "女", 78, 79, 80},
{3, "刘丽", 19, "女", 82, 59, 81},
{2, "许可", 18, "女", 90, 90, 90},
{4, "陈军", 23, "男", 88, 94, 94},
{7, "朱军", 24, "男", 87, 99, 95},
{6, "李鹏", 22, "男", 72, 93, 92},
};
fp = fopen("stud.dat", "wb"); // 模式:wb以只写方式打开或新建一个二进制文件,只允许写数据
if(fp == NULL)
{
printf("\t提示:不能创建stud.dat文件\n");
return;
}
for(i = 0; i < n; i++)
fwrite(&st[i], 1, sizeof(stud_type), fp);
fclose(fp);
printf(" 提示:文件stud.dat创建完毕\n");
}
/*-------------输出主文件stud.dat中的全部记录--------------*/
static void output_main_file(void)
{
FILE *fp;
stud_type st;
int i = 1;
fp = fopen("stud.dat", "rb");
if(fp == NULL)
{
printf(" 提示:不能读主文件stud.dat\n");
return;
}
printf("-------------------学生成绩表-------------------\n");
printf("记录号 学号 姓名 年龄 性别 语文 数学 英语\n");
whi