The provided C program implements a simple command-line utility for...

September 2, 2025 at 04:15 PM

#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> #define Cartella "TEST/" // Funzione per creare un documento void creaDocumento() { // Ottengo il nome del Documento char nome[64], contenuto[512]; printf("Nome documento: "); fgets(nome, sizeof(nome), stdin); nome[strcspn(nome, "\n")] = 0; // Ottengo il contenuto da salvare nel documento printf("Contenuto: "); fgets(contenuto, sizeof(contenuto), stdin); contenuto[strcspn(contenuto, "\n")] = 0; // Creo il commando da eseguire char comando[1024]; snprintf(comando, sizeof(comando),"mkdir -p %s && echo '%s' > %s%s.txt", Cartella, contenuto, Cartella, nome); // Eseguo il comando direttamente nel sistema system(comando); printf("Documento creato.\n"); } // Funzione per mostrare i documenti nella mia cartella void listaDocumenti() { // Questo e un commando automatico non necessita di input utente char comando[256]; snprintf(comando, sizeof(comando), "ls -1 %s", Cartella); printf("Lista documenti:\n"); system(comando); } // Funzione per leggere il contenuto di un documento void leggiDocumento() { // Ottengo il nome del Documento char nome[64]; printf("Nome documento da leggere: "); fgets(nome, sizeof(nome), stdin); nome[strcspn(nome, "\n")] = 0; // Creazione commando con input utente char comando[256]; snprintf(comando, sizeof(comando), "cat %s%s.txt", Cartella, nome); printf("Contenuto documento:\n"); // Eseguo il comando direttamente nel sistema system(comando); } // Funzione per eliminare documento void eliminaDocumento() { // Ottengo il nome del Documento char nome[64]; printf("Nome documento da eliminare: "); fgets(nome, sizeof(nome), stdin); nome[strcspn(nome, "\n")] = 0; // Creazione commando con input utente char comando[256]; snprintf(comando, sizeof(comando), "rm -f %s%s.txt", Cartella, nome); // Eseguo il comando direttamente nel sistema system(comando); printf("Documento eliminato (se esisteva).\n"); } int main() { int scelta; mkdir(Cartella, 0777); // Avvio una interazione persistente fra programma e utente per la gestione dei documenti do { printf("\nGestore Documenti\n"); printf("1) Crea Documento\n"); printf("2) Lista Documento\n"); printf("3) Leggi Documento\n"); printf("4) Elimina Documento\n"); printf("5) Finisci Gestione Documenti\n"); printf("Scelta: "); scanf("%d", &scelta); getchar(); switch (scelta) { case 1: creaDocumento(); break; case 2: listaDocumenti(); break; case 3: leggiDocumento(); break; case 4: eliminaDocumento(); break; case 5: printf("Chiusura programma.\n"); break; default: printf("Opzione non valida.\n"); } } while (scelta != 5); return 0; }

The provided C program implements a simple command-line utility for managing text documents. Here's what each part of the program does:

Overview:

The program uses system calls to execute operations like creating, listing, reading, and deleting text documents in a specific directory named TEST/. It repetitively interacts with the user through a menu-driven interface until the user chooses to exit.


Key Features and Behavior:

  1. Initialization (int main()):

    • The program ensures the directory TEST/ exists by using the mkdir function with permissions 0777.
    • Presents a persistent menu to the user with options to manage documents.
  2. Functions:

    • creaDocumento():

      • Prompts the user to provide a document name and its content.
      • Executes a system command to:
        1. Create the file within the TEST/ directory.
        2. Write the provided content into the file.
        • Example command: mkdir -p TEST/ && echo 'content' > TEST/document_name.txt.
      • Displays confirmation that the document has been created.
    • listaDocumenti():

      • Lists all files stored in the TEST/ directory.
      • Executes a system command: ls -1 TEST/, showing one file per line.
      • Displays the list of files to the user.
    • leggiDocumento():

      • Prompts the user to enter the name of a document they want to read (file name without .txt).
      • Executes a system command to display the content of the specified file using cat.
        • Example command: cat TEST/document_name.txt.
      • Displays the content if the file exists.
    • eliminaDocumento():

      • Prompts the user to enter the name of a document they want to delete.
      • Executes a system command to remove the specified file using rm.
        • Example command: rm -f TEST/document_name.txt.
      • Displays a message confirming the deletion of the document if it existed.
  3. Menu (do-while loop):

    • Displays the following options on a loop:
      1. Create a document.
      2. List documents.
      3. Read a document.
      4. Delete a document.
      5. Exit the program.
    • Based on the user's input (scelta), calls the corresponding function.
    • If an invalid option is entered, notifies the user before redisplaying the menu.

Notes on Behavior:

  • Directory Handling: The program creates the directory TEST/ at the start and saves all files there. It assumes this directory is writable.
  • Input Handling: User input is taken using fgets for strings and scanf for integers. The use of strcspn helps remove trailing newline characters that fgets may introduce.
  • System Commands: The program heavily relies on system() calls, making it simple but exposing it to potential risks like shell injection if inputs aren't carefully sanitized.
  • Permissions: The program assumes the user has appropriate permissions to perform file operations in the current working directory.

Example Interaction:

  1. Menu Prompt:

    Gestore Documenti
    1) Crea Documento
    2) Lista Documento
    3) Leggi Documento
    4) Elimina Documento
    5) Finisci Gestione Documenti
    Scelta: 
    
  2. Creating a Document (Option 1):

    • User enters document name: doc1
    • User enters content: Hello, World!
    • The program creates TEST/doc1.txt containing the text Hello, World!.
  3. Listing Documents (Option 2):

    • The program displays:
      Lista documenti:
      doc1.txt
      
  4. Reading a Document (Option 3):

    • User specifies the document doc1.
    • The program displays:
      Contenuto documento:
      Hello, World!
      
  5. Deleting a Document (Option 4):

    • User specifies the document doc1.
    • The program removes TEST/doc1.txt and confirms deletion.
  6. Exiting (Option 5):

    • The program terminates.

Risks & Potential Issues:

  1. Security Risk:

    • Using system() with user input directly introduces vulnerabilities (e.g., shell injection).
    • Inputs like name; rm -rf / or $(rm -rf /) could execute unintended destructive commands.
    • Solution: Avoid system() calls; use dedicated file I/O operations (fopen, fwrite, fread, etc.) for safer functionality.
  2. Error Handling:

    • The program doesn't check if the entered documents exist before reading or deleting.
    • It should verify the success of file operations to avoid errors or misleading confirmations.
  3. Cross-Platform Compatibility:

    • System commands (mkdir, ls, cat, rm) may not work on non-Unix-based operating systems (e.g., Windows without additional tools).

Summary:

The program is a basic document management system leveraging system commands to create, list, read, and delete text files in a dedicated directory (TEST/). While it demonstrates important programming concepts, it contains vulnerabilities and could be improved by using safer alternatives to system calls.

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