01: // generazione file CSV e binario a partire da struct
02: #include<stdio.h>
03: #include<stdlib.h>
04: 
05: // il file contiene, riga per riga, 4 numeri: 1 intero e 3 a virgola mobile separati da ","
06: // definisco opportuna struttura
07: 
08: #define MAXLEN (20)
09: 
10: struct student
11: {
12:   char name[MAXLEN], surname[MAXLEN];
13:   unsigned short score;
14: };
15: 
16: 
17: int main(int argc, char **argv){
18: 
19: 
20:   int nstudents;
21:   printf("Inserisci il numero degli studenti: ");
22:   scanf("%d", &nstudents);
23: 
24:   // alloco dinamicamente array per gestirli
25:   struct student *risultati = malloc(nstudents * sizeof(struct student));
26: 
27:   // ciclo per inserire i voti
28:   for(int i = 0; i < nstudents; ++i)
29:   {
30:     printf("Inserisci nome, cognome e voto dello studente #%d: ", i + 1);
31:     scanf(" %s %s %hu", risultati[i].name, risultati[i].surname, &risultati[i].score); // score e' un numero non un array e devo usare &
32:   }
33: 
34: 
35:   // salvo i risultati su due file differenti (ovvio che non ha molto senso, ma e' solo per esempio)
36:   // un file di tipo CSV e un file di tipo binario
37: 
38:   // CSV
39:   FILE *fp=fopen("esame.csv", "w");
40:   if(!fp)
41:   {
42:     perror("");
43:     exit(1);
44:   }
45: 
46:   for(int i = 0; i < nstudents; ++i)
47:   {
48:     fprintf(fp, "%s,%s,%hu\n", risultati[i].name, risultati[i].surname, risultati[i].score);
49:   }
50: 
51:   fclose(fp);
52: 
53: 
54:   // file binario
55:   fp=fopen("esame.dat", "wb");
56:   if(!fp)
57:   {
58:     perror("");
59:     exit(1);
60:   }
61:   fwrite(risultati, sizeof(struct student), nstudents, fp);
62:   fclose(fp);
63: 
64:   return 0;
65: }
66: 
67: 


Se avete commenti o osservaƶioni su questa pagina
mandate un messaggio di posta elettronica a bertoƶƶi@ce.unipr.it