随机文件排序存取--求助
//不知道哪里错了。帮帮忙#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NUM_MAX 4
//通过结构体中的zip进行排序
struct adress //结构体
{
char name[20];
char zip[11];
}ainfo;
//定义adress结构
struct adress adr[NUM_MAX]={
"pengshao","1578",
"wuli" ,"2576",
"pengwen" ,"990",
"shenzhen","55"
};
void _qs(FILE *fp,int left,int right);//排序接口
void swap_all_fileds(FILE *fp,long i,long j);//数据交换接口
char *get_zip(FILE *fp,long rec);//获取zip接口
int main(void)
{
FILE *fp;
register int i;
//创建file.dat二进制文件
if(!(fp=fopen("file.dat","wb")))
{
fprintf(stderr,"creat file.dat error.\n");
exit(1);
}
fwrite(adr,sizeof(ainfo),1,fp);
fclose(fp);
//打开file.dat二进制文件
if(!(fp=fopen("file.dat","rb+")))
{
fprintf(stderr,"open file.dat error.\n");
exit(1);
}
_qs(fp,0,NUM_MAX-1);
fclose(fp);
return 0;
}
//排序
void _qs(FILE *fp,int left,int right)
{
register long i,j;
char x[100];
strcpy(x,get_zip(fp,(long)(left+right)/2));
do
{
//扫描左边集合小于x的内容
while(strcmp(x,get_zip(fp,i))>0&&(i<right))
{
i++;
}
//扫描右边集合大于x的内容
while(strcmp(x,get_zip(fp,j))>0&&(j>left))
{
j--;
}
//交换数据
if(i<=j)
{
swap_all_fileds(fp,i,j);
i++;
j--;
}
}while(i<j);
if(left>j)
_qs(fp,left,(int)j);
if(i<right)
_qs(fp,(int)i,right);
}
void swap_all_fileds(FILE *fp,long i,long j)
{
char a[sizeof(ainfo)];
char b[sizeof(ainfo)];
//定位第i个位置
fseek(fp,sizeof(ainfo)*i,SEEK_SET);
//读取当前内容
fread(a,sizeof(ainfo),1,fp);
//定位第j个位置
fseek(fp,sizeof(ainfo)*j,SEEK_SET);
//保存当前内容
fread(b,sizeof(ainfo),1,fp);
//交换数据
fseek(fp,sizeof(ainfo)*j,SEEK_SET);
fwrite(a,sizeof(ainfo),1,fp);
fseek(fp,sizeof(ainfo)*i,SEEK_SET);
fwrite(b,sizeof(ainfo),1,fp);
}
char *get_zip(FILE *fp,long rec)
{
struct adress *p;
p=&ainfo;
fseek(fp,rec*sizeof(ainfo),SEEK_SET);
fread(p,sizeof(ainfo),1,fp);
return ainfo.zip;
}