I'm trying to print the contents of a binary file, but when I run the code, after inserting the various variables, they don't get printed, and the algorithm just ends. I think the fwrite is correct, but I'm not sure.
This is the code:
typedef struct{
char descrizione[80];
float voto;
}materia;
typedef struct{
char nome[80];
char cognome[80];
materia b[2];
}studente;
void lettura(FILE *fp, int n, studente a[n])
{
int i, j;
fp=fopen("file.bin","wb");
for(i=1;i<=n;i++)
{
printf("\nInserisci il nome del %d studente: ",i);
gets(a[i].nome);
printf("Inserisci il cognome del %d studente: ",i);
gets(a[i].cognome);
for(j=1;j<=2;j++)
{
printf("Inserisci la materia %d: ",j);
gets(a[i].b[j].descrizione);
printf("Inserisci il voto di %s %s in %s: ",a[i].nome,a[i].cognome,a[i].b[j].descrizione);
scanf("%f",&a[i].b[j].voto);
getchar();
}
fwrite(&a[i],sizeof(studente),1,fp);
}
fclose(fp);
}
int main(int argc, char *argv[]) {
int n=2, i=1;
studente a[n];
FILE *fp;
fp=fopen("file.bin","wb");
fclose(fp);
lettura(fp,n,a);
while(fread(&a[0],sizeof(studente),1,fp)>0)
{
printf("%s, %s, %s, %f",a[1].nome,a[i].cognome,a[i].b[i].descrizione,a[i].b[i].voto);
i++;
}
return 0;
}