Salve,
devo fare l'ordinamento degli elementi di un file ma non riesco a venirne a capo, potreste aiutarmi per favore?
l'esercizio consiste nell'inserire degli studenti all'interno di un file e stampare direttamente a video la lista ordinata in base al nome.
qui il codice:
codice:
#include <stdio.h>#include <stdlib.h>
#include <string.h>
struct tabella {
int code;
char name[20];
char surname[20];
};
void insert_sort ();
void menu();
void stamp();
void search();
void del();
int main () {
int comando;
do{
menu();
printf("\ncomando:\t ");
scanf("%d",&comando);
switch (comando) {
case 1:{
insert_sort();
break;
}
case 2: {
search();
break;
}
case 3: {
del();
break;
}
case 4: {
stamp();
break;
}
}
} while (true);
return 0;
}
void menu() {
printf("|||||||||||||||||||||||||||||");
printf("\n1)Registra uno studente");
printf("\n2)Cerca uno studente");
printf("\n3)Elimina uno studente");
printf("\n4)Visualizza elenco");
printf("|||||||||||||||||||||||||||||");
}
void insert_sort() {
FILE *fp;
int risp;
int i,j,temp;
struct tabella studenti;
fp=fopen("file.txt","a");
do {
printf("Inserisci matricola: ");
scanf("%d",&studenti.code);
printf("Inserisci nome: ");
scanf("%s",studenti.name);
printf("Inserisci cognome: ");
scanf("%s",studenti.surname);
fwrite(&studenti,sizeof(struct tabella),1,fp);
printf("Desideri continuare? (1=SI e 0=NO)");
scanf("%d",&risp);
}while (risp==1);
while(!feof) {
fread(&studenti,sizeof(struct tabella),1,fp);
for(i=0,j=1;j<feof(fp);i++,j++){
if(studenti[i].name>studenti[j].name) {
temp=studenti[i].name;
studenti[i].name=studenti[j].name;
studenti[j].name=temp; }
}
}
fwrite(&student,sizeof(struct tabella),1,fp);
fclose(fp);
}
void stamp(){
FILE *fp;
struct tabella studenti;
fp=fopen("file.txt","r");
while(fread(&studenti,sizeof(struct tabella),1,fp)>0) {
printf("Codice \t Nome \t Cognome \n");
printf("%d \t %s \t %s",studenti.code, studenti.name, studenti.surname);
}
fclose(fp);
}
grazie.