#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NUMCAT 6
#define LUNGCAT 6
#define LUNGPROD 4
#define EUROINLIRE 1936.27
struct prodotto {
char codice[LUNGPROD+1];
int lire;
float euro;
struct prodotto *next;
};
typedef struct prodotto Prodotto;
typedef Prodotto *ListaProdotti;
struct prodCategoria {
char cat[LUNGCAT+1];
ListaProdotti prodotti;
};
typedef struct prodCategoria ProdCategoria;
typedef ProdCategoria Magazzino[NUMCAT];
struct prezzoCategoria {
char cat[LUNGCAT+1];
float prezzo;
struct prezzoCategoria *next;
};
typedef struct prezzoCategoria PrezzoCategoria;
typedef PrezzoCategoria *ListaPrezzi;
void aggiornaPrezzi(Magazzino mag)
{
int i;
ListaProdotti prod;
for (i = 0; i < NUMCAT; i++) {
prod = mag[i].prodotti;
while (prod != NULL) {
prod->euro = prod->lire / EUROINLIRE;
prod = prod->next;
}
}
}
float prezzoMedio(ListaProdotti prod)
{
float prezzo = 0.0;
int num = 0;
while (prod != NULL) {
prezzo += prod->euro;
num++;
prod = prod->next;
}
if (num != 0)
prezzo /= num;
return prezzo;
}
void inserisciInListaOrdinata(ListaPrezzi *plis, char categoria[LUNGCAT+1],
float prezzo)
{
ListaPrezzi aux;
if (*plis == NULL || (*plis)->prezzo > prezzo) {
aux = malloc(sizeof(PrezzoCategoria));
aux->prezzo = prezzo;
strcpy(aux->cat, categoria);
aux->next = *plis;
*plis = aux;
} else
inserisciInListaOrdinata(&(*plis)->next, categoria, prezzo);
}
ListaPrezzi calcolaPrezziMedi(Magazzino mag)
{
int i;
ListaPrezzi lis = NULL;
for (i = 0; i < NUMCAT; i++)
if (mag[i].prodotti != NULL)
inserisciInListaOrdinata(&lis, mag[i].cat, prezzoMedio(mag[i].prodotti));
return lis;
}
void leggiMagazzino(char *nomefile, Magazzino mag)
{
FILE *fp;
int i, j, n;
ListaProdotti aux;
if ((fp = fopen(nomefile, "r")) == NULL) {
printf("Errore in apertura in lettura del file %s\n", nomefile);
exit(1);
}
for (i = 0; i < NUMCAT; i++) {
fscanf(fp, "%6s%d", mag[i].cat, &n);
mag[i].prodotti = NULL;
for (j = 0; j < n; j++) {
aux = malloc(sizeof(Prodotto));
fscanf(fp, "%4s%d", aux->codice, &aux->lire);
aux->euro = 0.0;
aux->next = mag[i].prodotti;
mag[i].prodotti = aux;
}
}
}
void stampaMagazzino(Magazzino mag)
{
int i;
ListaProdotti aux;
for (i = 0; i < NUMCAT; i++) {
printf("%6s", mag[i].cat);
aux = mag[i].prodotti;
while (aux != NULL) {
printf(" - %4s %d %g", aux->codice, aux->lire, aux->euro);
aux = aux->next;
}
printf("\n");
}
}
void stampaLista(ListaPrezzi lis)
{
while (lis != NULL) {
printf("%6s %g\n", lis->cat, lis->prezzo);
lis = lis->next;
}
}
int main (void)
{
char nomefile[256];
Magazzino mag;
ListaPrezzi lis;
printf("Immetti il nome del file: ");
scanf("%s", nomefile);
leggiMagazzino(nomefile, mag);
aggiornaPrezzi(mag);
printf("Magazzino:\n");
stampaMagazzino(mag);
printf("\nLista prezzi:\n");
lis = calcolaPrezziMedi(mag);
stampaLista(lis);
return 0;
}