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.");
}
Features of the Program
This program implements three key functionalities:
-
Add Contacts:
- Allows the user to input a name and a phone number.
- Stores the contact in a file named
Phonebook.txt
.
-
View Contacts:
- Reads and displays all the contacts stored in
Phonebook.txt
.
- Reads and displays all the contacts stored in
-
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
-
File Handling in C:
- Using
fopen
,fclose
, and file manipulation functions. - Handling errors when files cannot be opened or accessed.
- Using
-
Working with Strings:
- Using functions like
strcmp
andsscanf
for string comparisons and parsing.
- Using functions like
-
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
- Copy the code into a
.c
file and compile it with a C compiler (e.g.,gcc
):
gcc -o phonebook phonebook.c
- Run the compiled program:
./phonebook
Follow the on-screen instructions to add, view, or delete contacts.
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:
-
Input Validation:
- Ensure phone numbers are valid (e.g., only numeric characters).
- Prevent duplicate names in the phonebook.
-
Improved User Interface:
- Provide more detailed instructions.
- Allow multi-word names using
fgets
instead ofscanf
.
-
Enhanced File Handling:
- Encrypt data for security.
- Use a structured format (e.g., CSV or JSON).
-
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)