This C program is designed to manage and update logs...

August 26, 2025 at 09:56 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* o = (Ordine*)log; double totale = o->quantita * o->prezzo; printf("Interpretazione come Ordine:\n"); printf(" [%s] %s Q:%d Prezzo:%.2f Totale:%.2f\n", o->cid, o->prodotto, o->quantita, o->prezzo, totale); } // Aggiorna un log Cliente o 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* c = (Cliente*)logs[i]; if (strcmp(c->email, chiave) == 0) { printf("Trovato Cliente %s %s, aggiorno punti da %.2f a %.2f\n", c->nome, c->cognome, c->puntiFedelta, c->puntiFedelta + nuovoValore); c->puntiFedelta += nuovoValore; trovato = 1; gestisciLog(c); break; } } else { Ordine* o = (Ordine*)logs[i]; // Aggiorno il prezzo di un prodotto if (strcmp(o->cid, chiave) == 0) { printf("Trovato Ordine [%s], aggiorno prezzo da %.2f a %.2f\n", o->cid, o->prezzo, nuovoValore); o->prezzo = nuovoValore; trovato = 1; gestisciLog(o); 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* o = (Ordine*)logs[i]; fprintf(f, "%s %s %d %.2f\n", o->cid, o->prodotto, o->quantita, o->prezzo); } fclose(f); } int main() { char scelta[20]; printf("Vuoi aggiornare Cliente o 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 program is designed to manage and update logs for two types of records: Cliente (customer) records and Ordine (order) records. Here's what the different sections of the code do:

Struct Definitions

  1. Cliente Struct:

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

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

Core Functionalities

1. gestisciLog(void* log)

  • Interprets a generic log (assumes it to be an Ordine).
  • Calculates the total cost of an order (based on quantity and price) and prints the order details. This is called when working with Ordine.

2. aggiornaLog(const char* filename, const char* chiave, double nuovoValore, int isCliente)

This function is the core part of the program and is used to update the logs stored in files:

  • Parameters:

    • filename: The name of the log file (clienti.txt for customers or ordini.txt for orders).
    • chiave: The key used to identify the record to update (email for a customer or cid for an order).
    • nuovoValore: The new value to update (loyalty points for customers or price for orders).
    • isCliente: A flag indicating whether the log is for a customer (1) or an order (0).
  • Process:

    1. Opens the file for reading and reads the records into memory.
    2. Stores Cliente or Ordine records in a buffer.
      • For customers, it reads fields nome, cognome, email, and puntiFedelta into dynamically-allocated memory.
      • For orders, it reads fields cid, prodotto, quantita, and prezzo similarly.
    3. Searches the log entries for the specified key (chiave):
      • If it's a customer (isCliente = 1), it finds the customer by matching their email and updates their loyalty points (puntiFedelta).
      • If it's an order (isCliente = 0), it finds the order by matching the customer ID (cid) and updates the price.
    4. If the record is found and updated, it rewrites the updated records back to the file.
    5. If the record is not found, it prints an appropriate message and does nothing further.

Main Execution

  1. The program starts by asking the user whether they want to update a "Cliente" (customer) or "Ordine" (order).
  2. Depending on the user's choice:
    • If "Cliente":
      1. Prompts for the customer's email and the number of loyalty points to add.
      2. Calls aggiornaLog with isCliente = 1 to update the log in clienti.txt.
    • If "Ordine":
      1. Prompts for the order's cid and the new price.
      2. Calls aggiornaLog with isCliente = 0 to update the log in ordini.txt.
  3. If the user's input is invalid, it prints an error message.

File Handling

  • The program assumes the existence of two text files: clienti.txt (for customer logs) and ordini.txt (for order logs). These files should be formatted as:

    • clienti.txt:
      Nome Cognome Email PuntiFedelta
      
    • ordini.txt:
      CustomerID Prodotto Quantita Prezzo
      
  • When updating, it reads the file, modifies the data in memory, and writes the updated data back to the file. If the file isn't found, it prints an error message and exits the function.


Example Use Case

Updating Customer Points

  1. The user selects "Cliente".
  2. The program asks for the email address of the customer and the number of points to add.
  3. It searches clienti.txt for the customer by their email:
    • If found, updates the loyalty points.
    • If not, prints "Record [email] non trovato."
  4. Writes the updated data back to clienti.txt.

Updating Order Price

  1. The user selects "Ordine".
  2. The program asks for the cid of the order and the new price.
  3. It searches ordini.txt for the order by its cid:
    • If found, updates the price.
    • If not, prints "Record [cid] non trovato."
  4. Writes the updated data back to ordini.txt.

Issues in the Code

  1. Memory Leaks:

    • Allocations for Cliente and Ordine using malloc are not freed after use, leading to memory leaks.
  2. Data Mismanagement:

    • The program tries to handle both Cliente and Ordine logs using a single buffer (logs[100]), assuming they have the same structure, which can cause undefined behavior when a gestisciLog function is called on a Cliente object.
  3. Incorrect Output for Customers:

    • The gestisciLog function assumes its input is always an Ordine, but it is called with a Cliente in the customer update process. This leads to incorrect and possibly undefined behavior.

In Summary

The program:

  • Reads and updates customer or order logs based on user input.
  • Writes updated information back to the corresponding log file.
  • Relies on correct input formatting and file existence, with some implementation issues.
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