codice:
#include <stdio.h>
#include <string.h>
#define n 100
struct tracce {
char titolo[20];
int copie;
}tra[n];
void ricerca (struct tracce track[], char key[], int low, int high, int v);
int main()
{
int i, j, k, V;
char buffer[20];
char tit[20];
int num, app;
char chiave[20];
FILE *cfPtr;
if ((cfPtr = fopen("brani.dat", "w")) == NULL ) {
printf("IL file non può essere aperto.\n");
} else {
i = 0;
printf("Inserisci titolo e copie vendute\n");
printf("Inserisci EOF per terminare\n");
scanf("%s%d\n", tra[i].titolo, &tra[i].copie);
fprintf(cfPtr, "%30s", "BRANI\n");
fprintf(cfPtr, "%20s %20s", "TITOLO", "COPIE VENDUTE\n");
fprintf(cfPtr, "%20s %20d\n", tra[i].titolo, tra[i].copie);
while( !feof(stdin) ) {
i++;
scanf("%s%d\n", tra[i].titolo, &tra[i].copie);
fprintf(cfPtr, "%20s %20d\n", tra[i].titolo, tra[i].copie);
}
fclose(cfPtr);
}
printf("\n\n");
for ( j = 0; j < i; j++ ) {
for ( k = j + 1; k <= i; k++ ) {
if (strcmp(tra[j].titolo, tra[k].titolo) > 0 ) {
strcpy(buffer, tra[j].titolo);
strcpy(tra[j].titolo, tra[k].titolo);
strcpy(tra[k].titolo, buffer);
app = tra[j].copie;
tra[j].copie = tra[k].copie;
tra[k].copie = app;
}
}
}
printf("%30s", "BRANI\n");
printf("%20s %20s", "TITOLO", "COPIE VENDUTE\n");
for ( j = 0; j <= i; j++ ) {
printf("%20s %19d\n", tra[j].titolo, tra[j].copie);
}
printf("Inserisci il titolo da cercare : \n");
scanf("%s", chiave);
ricerca(tra, chiave, 0, i, V);
printf("%d\n", V);
if ( V = 1 ) {
printf("Il brano cercato è stato trovato\n");
} else if ( V == 0 )
{
printf("Il brano cercato NON è stato trovato\n");
}
return 0;
}
void ricerca (struct tracce track[], char key[], int low, int high, int v)
{
int middle;
v = 0;
while (low <= high) {
middle = (low + high) / 2;
if (strcmp (key, track[middle].titolo) == 0) {
v = 1;
} else if (strcmp(key, track[middle].titolo) < 0) {
high = middle - 1;
} else {
low = middle + 1;
}
}
}