DEV Community

Cover image for Practicing C: Building a Simple Phonebook Application
Davide
Davide

Posted on

Practicing C: Building a Simple Phonebook Application

If you're learning C programming, practical exercises can be the best way to solidify your skills. In this post, I'll walk you through a project I worked on recently: creating a simple phonebook application. This program allows you to add, view, and delete contacts, demonstrating file handling and basic data management in C.


Code Walkthrough

Here's the complete code for the phonebook application:

#include <stdio.h>
#include <string.h>

// Function declarations
void addContact(char name[], char number[]);
void viewContacts();
void deleteContact(char name[]);

int main() {
    int choice;
    char name[20];
    char number[20];

    printf("-- Welcome to your phonebook! -- \n");

    do {
        // Display menu
        printf("\nWhat operation would you like to perform?\n");
        printf("1. Create a new contact\t 2. View your phonebook\t 3. Delete a contact\t 4. Exit\n");
        scanf("%d", &choice);

        switch (choice) {
            case 1:
                // Adding a new contact
                printf("Great, let's create a new contact: \n");
                printf("Enter the contact's name:\n");
                scanf("%s", name);
                printf("Now enter the phone number:\n");
                scanf("%s", number);
                addContact(name, number);
                break;
            case 2:
                // Viewing the phonebook
                printf("Here is your phonebook: \n");
                viewContacts();
                break;
            case 3:
                // Deleting a contact
                printf("Write the name of the contact you want to delete:\n");
                scanf("%s", name);
                deleteContact(name);
                break;
        }
    } while (choice != 4); // Loop until the user selects "Exit"

    return 0;
}

// Function to add a contact to the phonebook
void addContact(char name[], char number[]) {
    FILE *pFile;
    pFile = fopen("Phonebook.txt", "a");
    if (pFile == NULL) {
        printf("Error opening the phonebook.");
        return;
    }
    fprintf(pFile, "Name: %s \t Number: %s\n", name, number);
    printf("The contact has been created! \n");
    fclose(pFile);
}

// Function to view all contacts in the phonebook
void viewContacts() {
    char fileContent[200];
    FILE *pFile;
    pFile = fopen("Phonebook.txt", "r");

    while (fgets(fileContent, sizeof(fileContent), pFile)) {
        printf("\n%s", fileContent);
    }

    fclose(pFile);    
}

// Function to delete a contact from the phonebook
void deleteContact(char name[]) {
    FILE *pFile, *pTrash;
    char line[200], contactName[20], contactNumber[20];

    pFile = fopen("Phonebook.txt", "r");
    pTrash = fopen("Trash.txt", "w");

    if (pFile == NULL || pTrash == NULL) {
        printf("Error opening the file.");
        return;
    }

    while (fgets(line, sizeof(line), pFile)) {
        sscanf(line, "Name: %s \t Number: %s\n", contactName, contactNumber);
        if (strcmp(name, contactName) != 0) {
            fputs(line, pTrash);
        }
    }

    fclose(pFile);
    fclose(pTrash);

    // Replace the old phonebook with the updated version
    remove("Phonebook.txt");
    rename("Trash.txt", "Phonebook.txt");
    printf("The contact has been deleted.");
}
Enter fullscreen mode Exit fullscreen mode

Features of the Program

This program implements three key functionalities:

  1. Add Contacts:

    • Allows the user to input a name and a phone number.
    • Stores the contact in a file named Phonebook.txt.
  2. View Contacts:

    • Reads and displays all the contacts stored in Phonebook.txt.
  3. Delete Contacts:

    • Removes a contact based on the name entered by the user.
    • Creates a temporary file to filter out the deleted contact, then replaces the original file.

Key Learnings from This Exercise

  1. File Handling in C:

    • Using fopen, fclose, and file manipulation functions.
    • Handling errors when files cannot be opened or accessed.
  2. Working with Strings:

    • Using functions like strcmp and sscanf for string comparisons and parsing.
  3. Basic Data Management:

    • Storing and organizing data in a simple text file.
    • Replacing or updating file contents by creating temporary files.

How to Test the Code

  1. Copy the code into a .c file and compile it with a C compiler (e.g., gcc):
   gcc -o phonebook phonebook.c
Enter fullscreen mode Exit fullscreen mode
  1. Run the compiled program:
   ./phonebook
Enter fullscreen mode Exit fullscreen mode
  1. Follow the on-screen instructions to add, view, or delete contacts.

  2. Open Phonebook.txt to verify that the data is being stored as expected.


Potential Enhancements

This program is a great starting point, but here are a few improvements you can try:

  1. Input Validation:

    • Ensure phone numbers are valid (e.g., only numeric characters).
    • Prevent duplicate names in the phonebook.
  2. Improved User Interface:

    • Provide more detailed instructions.
    • Allow multi-word names using fgets instead of scanf.
  3. Enhanced File Handling:

    • Encrypt data for security.
    • Use a structured format (e.g., CSV or JSON).
  4. Advanced Features:

    • Implement a search functionality to find contacts quickly.
    • Sort the phonebook alphabetically.

Final Thoughts

This exercise helped me strengthen my understanding of file handling and basic data management in C. It’s a simple yet practical program that can serve as a foundation for more complex projects. If you’re new to C, give it a try—it’s a fun and rewarding way to practice programming!

Top comments (0)