tienda

 avatar
unknown
plain_text
2 years ago
2.9 kB
13
Indexable
#include <stdio.h>
#include <stdlib.h>
#define MAX_STRING_LENGTH 80

typedef struct
{
    char descripcion[MAX_STRING_LENGTH];
    float precio;
    char iva;
} Producto;

typedef struct
{
    Producto *productos;
    int num_producto;
} Mercado;

int cargarProductos(Mercado *m, char filename[]) {

    FILE* file;
    int flag = 0;
    int i = 0;
    char basura;

    file = fopen(filename, "r");
    if(file == NULL) {
        printf("Error opening file\n");
        flag = 0;
    } else {

        fscanf(file, "%d", &m->num_producto); // (*m).num_producto

        m->productos = (Producto*) malloc(sizeof(Producto) * m->num_producto); // (*m).productos

        if(m->productos == NULL) {
            printf("Error allocating memory\n");
            flag = 0;
        } else {
            while(!feof(file)) {
                fscanf(file, "%s", m->productos[i].descripcion);
                fscanf(file, "%f", &m->productos[i].precio);
                fscanf(file, "%c", &basura);
                fscanf(file, "%c", &m->productos[i].iva);
                i++;
            }
            flag = 1;
            printf("%d productos cargados en caja\n", (*m).num_producto);
            fclose(file);
        }
    }

    return flag;

}


void mostrarTotal(Mercado *m) {

    int i = 0;
    float total = 0;

    for(i = 0; i < m->num_producto; i++) {
        if(m->productos[i].iva == 'O') {
            total += m->productos[i].precio * 1.10; // equivale a total = total + lalala
        } else {
            total += m->productos[i].precio * 1.21;
        }
    }

    printf("Total: %.2f\n", total);

}
void freeUpMemory(Producto **productos) {

    printf("Liberando memoria de caja...\n");

    free(*productos);
    *productos = NULL; //SIEMPRE

}

int main()
{
    char filename[100];
    Mercado mercado;
    Mercado *m;
    m = &mercado;
    int opcion = 0, flag = 0;
    do
    {
        printf("MENU (1. Cargar productos | 2. Mostrar total | 3. Cerrar caja)\n");
        do
        {
            printf("Opcion: ");
            scanf("%d", &opcion);
        } while (opcion < 1 || opcion > 4);
        switch (opcion)
        {
        case 1:
            printf("Fichero: ");
            scanf("%s", filename);
            flag = cargarProductos(m, filename);
            break;
        case 2:
            if (flag != 0)
            {
                mostrarTotal(m);
                break;
            }
            else
            {
                printf("No se puede mostrar ganancia, porque los productos no se han cargado correctamente\n");
                break;
            }
        case 3:
            if (flag != 0)
            {
                freeUpMemory(&m->productos); //equivale a &(*m).productos... EL PUNTERO DEL PUNTERO!
                printf("Cerrando caja...");
            }
            break;
        }
    } while (opcion != 3);
return 0;
}
Editor is loading...