#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct
{
char* name;
int vote;
} SUBJECT;
SUBJECT* subjects;
int subjectsn;
char* getFilename(void)
{
static char* r;
int n = 0;
char fn[80];
while (1)
{
sprintf(fn, "report%i.rpt", n);
FILE* f = fopen(fn, "r");
if (!f)
{
sprintf(fn, "report%i", n);
r = (char*) malloc(strlen((char*) &fn));
strcpy(r, (char*) &fn);
return r;
}
n++;
}
}
int main(void)
{
subjectsn = 0;
printf("Calcolatore media pagella\n");
printf("\nInserisci ogni materia e ogni voto, se hai finito scrivi \"ok\" nel nome materia.\n");
while (1)
{
char name[80];
int vote;
printf("\n_____________________________\n\n");
printf("Nome materia: ");
scanf("%s", (char*) &name);
if (strcmp(name, "ok") == 0) break;
printf("Voto: ");
scanf("%i", &vote);
printf("\nAggiungo... ");
subjects = (SUBJECT*) realloc(subjects, (subjectsn + 1) * sizeof(SUBJECT));
subjects[subjectsn].name = (char*) malloc(strlen((char*) &name));
strcpy(subjects[subjectsn].name, (char*) &name);
subjects[subjectsn].vote = vote;
subjectsn++;
printf("OK\n");
}
printf("_____________________________\n");
printf("\nTerminata aggiunta, creo il report...\n");
int sum = 0;
int i; for (i = 0; i < subjectsn; i++)
sum += subjects[i].vote;
float aver;
aver = (float)((float)sum / (float)subjectsn);
printf("\nReport:");
printf("\n_____________________________\n");
for (i = 0; i < subjectsn; i++)
printf("\n%s\n\t%i\n", subjects[i].name, subjects[i].vote);
printf("_____________________________\n");
printf("\nMedia:\n\t%f\n", aver);
printf("_____________________________\n\n");
printf("Salvataggio report... ");
char* of = getFilename();
char* filename = (char*) malloc(strlen(of) + strlen(".rpt"));
strcpy(filename, of);
strcat(filename, ".rpt");
FILE* f = fopen(filename, "w+");
fprintf(f, "Report voti materie e media aritmetica :: Calcolatore media pagella\n\n");
fprintf(f, "\nReport:");
fprintf(f, "\n_____________________________\n\n");
for (i = 0; i < subjectsn; i++)
fprintf(f, "%s\n\t%i\n\n", subjects[i].name, subjects[i].vote);
fprintf(f, "_____________________________\n");
fprintf(f, "\nMedia:\n\t%f\n", aver);
fprintf(f, "_____________________________\n\n");
fclose(f);
printf("OK\n");
printf("Salvataggio file dati... ");
filename = (char*) malloc(strlen(of) + strlen(".dat"));
strcpy(filename, of);
strcat(filename, ".dat");
f = fopen(filename, "wb");
fputc(0xAF, f);
for (i = 0; i < subjectsn; i++)
{
fputc(0xBC, f);
fprintf(f, "%s", subjects[i].name);
fputc(0xCD, f);
fputc(subjects[i].vote, f);
fputc(0xDE, f);
}
fputc(0xEF, f);
printf("OK\n");
printf("_____________________________\n\n");
printf("Grazie per l'utilizzo! by Gi@cky98\n");
printf("_____________________________\n");
}