1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
| #include <stdio.h>
struct article
{
int rec;
int no;
};
void main()
{
FILE *f;
int i,j,k,sw,n,G,D,T,M;
struct article data[100],tmp,recherche;
long recno;
i=0;
f=fopen("carnet.dat","rb");
fread(&data[i],sizeof(struct article),1,f);
while(!feof(f))
{
i++;
fread(&data[i],sizeof(struct article),1,f);
}
fclose(f);
k=i-1;
sw=0;
while(k>=0 && sw==0)
{
sw=1;
for(j=0;j<i;j++)
{
if(data[j].no>data[j+1].no)
{
tmp=data[j];
data[j]=data[j+1];
data[j+1]=tmp;
sw=0;
}
}
k--;
}
j=0;
while(j<i)
{
printf(" %3d ) %8d no rec : %3d\n",j+1,data[j].no,data[j].rec);
j++;
}
printf("\n\nle numero a rechercher > ");scanf("%d",&n);
//recherche dichotomique
T=0;
G=0;
D=j-1;
while(T==0 && G<=D)
{
M=(G+D)/2;
if(n==data[M].no)
{
T=1;
}
else
{
if(n<data[M].no)
{
D=M-1;
}
else
{
if(n>data[M].no)
{
G=M+1;
}
}
}
}
if(T==1)
{
f=fopen("carnet.dat","rb");
recno=data[M].rec;
fseek(f,recno,SEEK_SET);
fread(&recherche,sizeof(struct article),1,f);
printf("rec : %d nombre : %d",data[M].rec,recherche.no);
}
else
{
printf("\n\n\n le numero rechercher est absent du fichier");
}
getch();
} |
Partager