This C code implements a program to manage and update...

August 27, 2025 at 01:49 PM

#include <stdio.h> #include <stdlib.h> #include <string.h> // Struct Cliente typedef struct { char nome[20]; char cognome[20]; char email[30]; double puntiFedelta; } Cliente; // Struct Ordine typedef struct { char cid[20]; int quantita; double prezzo; char prodotto[20]; } Ordine; // Gestore unico che interpreta sempre come Ordine void gestisciLog(void* log) { Ordine* ordine = (Ordine*)log; double totale = ordine->quantita * ordine->prezzo; printf("Interpretazione come Ordine:\n"); printf(" [%s] %s Q:%d Prezzo:%.2f Totale:%.2f\n", ordine->cid, ordine->prodotto, ordine->quantita, ordine->prezzo, totale); } // Aggiorna un log Cliente ordine Ordine void aggiornaLog(const char* filename, const char* chiave, double nuovoValore, int isCliente) { FILE* f = fopen(filename, "r"); if (!f) { perror("Errore apertura file log"); return; } // Buffer log void* logs[100]; int n = 0; // Controllo se isCLiente == 1 oppure e un ordine if (isCliente) { Cliente* clienti = malloc(sizeof(Cliente) * 100); // Leggo dal log e salvo nel buffer i dati letti while (fscanf(f, "%19s %19s %29s %lf", clienti[n].nome, clienti[n].cognome, clienti[n].email, &clienti[n].puntiFedelta) == 4) { logs[n] = &clienti[n]; n++; } } else { // Gestisco lato Ordini Ordine* ordini = malloc(sizeof(Ordine) * 100); // Leggo dal log e salvo nel buffer i dati letti while (fscanf(f, "%19s %19s %d %lf", ordini[n].cid, ordini[n].prodotto, &ordini[n].quantita, &ordini[n].prezzo) == 4) { logs[n] = &ordini[n]; n++; } } fclose(f); // Aggiorno i dati letti dai log int trovato = 0; for (int i = 0; i < n; i++) { // Aggiungo al cliente punti fedelta if (isCliente) { Cliente* cliente = (Cliente*)logs[i]; if (strcmp(cliente->email, chiave) == 0) { printf("Trovato Cliente %s %s, aggiorno punti da %.2f a %.2f\n", cliente->nome, cliente->cognome, cliente->puntiFedelta, cliente->puntiFedelta + nuovoValore); cliente->puntiFedelta += nuovoValore; trovato = 1; gestisciLog(cliente); break; } } else { Ordine* ordine = (Ordine*)logs[i]; // Aggiorno il prezzo di un prodotto if (strcmp(ordine->cid, chiave) == 0) { printf("Trovato Ordine [%s], aggiorno prezzo da %.2f a %.2f\n", ordine->cid, ordine->prezzo, nuovoValore); ordine->prezzo = nuovoValore; trovato = 1; gestisciLog(ordine); break; } } } if (!trovato) { printf("Record %s non trovato.\n", chiave); return; } // Avvio il log in modalita scrittura f = fopen(filename, "w"); if (!f) { perror("Errore scrittura file log"); return; } // Riscrivo il log con dati aggiornati for (int i = 0; i < n; i++) { Ordine* ordine = (Ordine*)logs[i]; fprintf(f, "%s %s %d %.2f\n", ordine->cid, ordine->prodotto, ordine->quantita, ordine->prezzo); } fclose(f); } int main() { char scelta[20]; printf("Vuoi aggiornare Cliente ordine Ordine? "); scanf("%19s", scelta); // Gestisco la scelta del utente di quale log aggiornare if (strcmp(scelta, "Cliente") == 0 || strcmp(scelta, "cliente") == 0) { char email[30]; double punti; printf("Inserisci email cliente da aggiornare: "); scanf("%29s", email); printf("Punti omaggio: "); scanf("%lf", &punti); // Passo al metodo di aggiornamento il nome del log email cliente e punti da aggiungere con un flag=1 che indica cliente aggiornaLog("clienti.txt", email, punti, 1); } else if (strcmp(scelta, "Ordine") == 0 || strcmp(scelta, "ordine") == 0) { char cid[20]; double prezzo; printf("Inserisci CID ordine da aggiornare: "); scanf("%19s", cid); printf("Nuovo prezzo: "); scanf("%lf", &prezzo); // Passo al metodo di aggiornamento il nome del log ordini id prodotto nuovo prezzo e flag=0 indicando ordini aggiornaLog("ordini.txt", cid, prezzo, 0); } else { printf("Scelta non valida.\n"); } return 0; }

This C code implements a program to manage and update logs, storing information about either customers (Cliente) or orders (Ordine). Here's a breakdown of what the code does:


1. Structures Defined

  • Cliente:

    • Represents a customer, with fields for a name (nome), surname (cognome), email, and loyalty points (puntiFedelta).
  • Ordine:

    • Represents an order, with fields for a customer ID (cid), product quantity (quantita), price (prezzo), and product name (prodotto).

2. Functionality

gestisciLog(void* log)

  • Interprets raw log data as an Ordine object, calculates the total cost (quantita * prezzo), and prints the order details.
  • This function is generic and always interprets the log as an order, even if it gets passed Cliente data (may lead to undefined behavior when used incorrectly).

aggiornaLog

  • This is the main function used for updating log files (either customer log clienti.txt or order log ordini.txt).
  • Steps:
    1. Opens the log file (clienti.txt for customers or ordini.txt for orders) in read mode.
    2. Reads log data into memory, storing it as either Cliente or Ordine objects.
    3. Searches for a record that matches the provided key (chiave), which is the email for customers or the order ID (cid) for orders.
      • If a customer (isCliente == 1): Updates the customer's loyalty points.
      • If an order (isCliente == 0): Updates the order's product price.
    4. If a matching record is found and updated, writes the updated data back to the log file in write mode.
    5. If no record matches the key, prints a message stating it wasn't found.

Note: The function dynamically allocates memory (malloc), but there is no proper cleanup (free), which may cause memory leaks.


main

  • Requests the user to choose whether to update a customer ("Cliente") or order ("Ordine").
  • Based on the user's choice:
    • If "Cliente":
      • Asks for the customer's email and the points to award, then calls aggiornaLog with isCliente = 1.
    • If "Ordine":
      • Asks for the order ID (cid) and the new price, then calls aggiornaLog with isCliente = 0.
    • If the input doesn't match either option, the program prints that the choice is invalid and exits.

Output is written to clienti.txt (for customers) or ordini.txt (for orders) based on the operation.


Usage

  1. Manage Customers:
    • Reads from clienti.txt with the format nome cognome email puntiFedelta.
    • Updates the loyalty points for the specified customer based on their email address.
  2. Manage Orders:
    • Reads from ordini.txt with the format cid prodotto quantita prezzo.
    • Updates the price of the product in the specified order, identified by its cid.

Example Workflow

File: clienti.txt

Mario Rossi mario.rossi@example.com 150.0
Luigi Bianchi luigi.bianchi@example.com 200.0

File: ordini.txt

123 pasta 5 3.50
456 latte 2 1.80
  1. User selects "Cliente".

    • Enters email: mario.rossi@example.com.
    • Enters points to add: 50.
    • Result: The updated clienti.txt will be:
      Mario Rossi mario.rossi@example.com 200.0
      Luigi Bianchi luigi.bianchi@example.com 200.0
      
  2. User selects "Ordine".

    • Enters CID: 123.
    • Enters new price: 4.5.
    • Result: The updated ordini.txt will be:
      123 pasta 5 4.50
      456 latte 2 1.80
      

Issues and Observations

  1. Memory Management:

    • Dynamic memory is used (malloc), but it is not properly freed, leading to memory leaks.
  2. Error Handling:

    • If the logs are not correctly formatted or the file is missing, the program may fail or behave unexpectedly.
  3. gestisciLog Misuse:

    • The gestisciLog function assumes all logs are Ordine structures, even if Cliente data is passed. This could lead to undefined behavior or incorrect interpretation.
  4. File Overwrite:

    • The entire file is rewritten even if only one record is updated.

Summary

This code allows the user to update customer loyalty points or order prices in separate log files (clienti.txt and ordini.txt). It parses the files, modifies relevant entries, and saves the updates. Improvements are needed for memory management, error handling, and the generic log interpretation approach.

Generate your own explanations
Download our vscode extension
Read other generated explanations

Built by @thebuilderjr
Sponsored by beam analytics
Read our terms and privacy policy
Forked from openai-quickstart-node