This code implements a simple text-based database management program in...

September 3, 2025 at 10:53 PM

#include <stdio.h> #include <stdlib.h> #include <string.h> #define DataBase "TEST/database.txt" // Funzione per aggiungere un record alla base di dati void aggiungiRecord() { char chiave[255], valore[255], record[512]; // Prendo in input la chaive e il valore da aggiungere alla base di dati printf("Inserisci chiave: "); fgets(chiave, sizeof(chiave), stdin); chiave[strcspn(chiave, "\n")] = 0; printf("Inserisci valore: "); fgets(valore, sizeof(valore), stdin); valore[strcspn(valore, "\n")] = 0; // COncateno la chiave al valore separandoli con un : snprintf(record, sizeof(record), "%s:%s\n", chiave, valore); // Accedo al file e concateno la nuova riga alla fine del file FILE *file = fopen(DataBase, "a"); if (file) { fputs(record, file); fclose(file); printf("Record aggiunto.\n"); } else { perror("Errore apertura database"); } } // Funzione per settaciare una base di dati per dato una chiave void cercaRecord() { char chiave[64], riga[512]; // Prendo in input la chaive da cercare printf("Chiave da cercare: "); fgets(chiave, sizeof(chiave), stdin); chiave[strcspn(chiave, "\n")] = 0; // Accedo al file data base FILE *file = fopen(DataBase, "r"); if (!file) { perror("Errore apertura database"); return; } // Controllo riga per riga se la chiave e presente all'interno della base di dati int trovato = 0; while (fgets(riga, sizeof(riga), file)) { if (strstr(riga, chiave)) { fputs(riga, stdout); trovato = 1; } } if (!trovato) printf("Nessun record trovato.\n"); fclose(file); } // Comparator per qsort int comp(const void *a, const void *b) { const char *pa = *(const char **)a; const char *pb = *(const char **)b; return strcmp(pa, pb); } // Funzione per ordinare la base di dati void ordinaDatabase() { // Accedo alla base di dati in modalita lettura FILE *file = fopen(DataBase, "r"); if (!file) { perror("Errore apertura database"); return; } char *righe[2048]; int count = 0; char buffer[2048]; // Salvo il contenuto del file nel buffer while (fgets(buffer, sizeof(buffer), file) && count < 2048) { // Duplico le righe salvate nel buffe in righe righe[count] = strdup(buffer); if (!righe[count]) { perror("malloc fallita"); fclose(file); return; } count++; } fclose(file); // Funzione per il sorting delle righe qsort(righe, count, sizeof(char *), comp); // Apro il file in modalita scrittura file = fopen(DataBase, "w"); if (!file) { perror("Errore scrittura database"); for (int i = 0; i < count; i++) free(righe[i]); return; } // Riscrivo le righe riordinate nel file for (int i = 0; i < count; i++) { fputs(righe[i], file); free(righe[i]); } fclose(file); printf("Database ordinato.\n"); } // Funzione per la stampa della base di dati void mostraDatabase() { // Accedo al file FILE *file = fopen(DataBase, "r"); if (!file) { perror("Errore apertura database"); return; } // Stampo il contenuto della base di dati riga per riga char riga[512]; printf("Contenuto database:\n"); while (fgets(riga, sizeof(riga), file)) { fputs(riga, stdout); } fclose(file); } int main() { int scelta; // In caso la base di dati non ci sia ancora lo creo FILE *file = fopen(DataBase, "a"); if (file) fclose(file); // Menu persistente per l'interazione utente programma do { printf("\nGestore Database di Testo\n"); printf("1) Aggiungi Record\n"); printf("2) Cerca Record\n"); printf("3) Ordina Base di Dati\n"); printf("4) Mostra Base di Dati\n"); printf("5) Esci\n"); printf("Scelta: "); if (scanf("%d", &scelta) != 1) { while (getchar() != '\n'); continue; } getchar(); // consuma newline switch (scelta) { case 1: aggiungiRecord(); break; case 2: cercaRecord(); break; case 3: ordinaDatabase(); break; case 4: mostraDatabase(); break; case 5: printf("Chiusura.\n"); break; default: printf("Scelta non valida.\n"); } } while (scelta != 5); return 0; }

This code implements a simple text-based database management program in C. Let's break down its functionality and what each part of the code does:

Components of the Code:

  1. DataBase Definition

    • The database file is defined as a text file, "TEST/database.txt". Records are managed and stored in this file.
  2. Functions:

    • aggiungiRecord()

      • Prompts the user to input a key and a value.
      • Combines the key and value into a single record in the format key:value.
      • Appends the new record as a new line to the database text file.
    • cercaRecord()

      • Asks the user for a key to search for in the database.
      • Opens the database file and reads it line by line.
      • Prints any record that contains the input key.
      • If the key is not found, it reports "Nessun record trovato" (No record found).
    • ordinaDatabase()

      • Reads all the lines from the database into memory (up to a fixed limit of 2048 lines).
      • Uses the qsort function to sort the lines in lexical order.
      • Writes the sorted lines back to the database file, overwriting the previous contents.
      • Frees memory for the dynamically allocated lines.
    • mostraDatabase()

      • Reads and displays all the contents of the database file, line by line.
  3. Main Function:

    • Implements a text-based menu system for interacting with the user.
    • Options:
      1. Add a new record to the database.
      2. Search for a record by key.
      3. Sort the database alphabetically.
      4. Display all the records in the database.
      5. Exit the program.
    • Ensures the database file is created if it doesn't already exist (using fopen with the "a" mode).
    • Continues to display the menu until the user chooses to exit.

How the Program Works:

  • The program operates on a simple file-based database. Each record in the database is stored in the format:
    key:value
    
  • Users can:
    • Add new records to the file.
    • Search for specific records containing a particular substring (key).
    • Sort the database in alphabetical order based on the lines (keys and values combined).
    • Display all records in the database file.

Possible Limitations:

  1. Key Duplication: The program doesn't enforce unique keys, so the same key can be added multiple times with different values.
  2. Memory Usage: Sorting the database requires reading all its lines into memory, which could fail or lead to high memory usage for very large databases.
  3. Error Handling: The program does basic error checking (e.g., ensuring files can be opened), but additional checks (e.g., malformed input) might be beneficial.
  4. Search Behavior: The search function matches any line containing the key as a substring, which might lead to unintended results if key overlaps with part of a value.

Summary:

This program is a basic implementation of a text-based database with functionalities for adding, searching, sorting, and displaying records. It uses standard C file I/O functions and manual memory management to handle database interactions. This makes it a useful tool for managing small datasets or for educational purposes to understand file-based database concepts in C.

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