Home > Backend Development > C++ > Practicing C: Building a Simple Phonebook Application

Practicing C: Building a Simple Phonebook Application

Barbara Streisand
Release: 2025-01-22 04:24:14
Original
1010 people have browsed it

Practicing C: Building a Simple Phonebook Application

One of the best ways to learn C programming is through practical exercises. This article will take you step-by-step through a project I recently completed: creating a simple phone book application. This program allows you to add, view, and delete contacts and demonstrates file handling and basic data management in C.


Detailed code explanation

Here is the complete code for the phone book application:

<code class="language-c">#include <stdio.h>
#include <string.h>

// 函数声明
void addContact(char name[], char number[]);
void viewContacts();
void deleteContact(char name[]);

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

    printf("-- 欢迎使用您的电话簿! -- \n");

    do {
        // 显示菜单
        printf("\n您想执行什么操作?\n");
        printf("1. 创建新联系人\t 2. 查看电话簿\t 3. 删除联系人\t 4. 退出\n");
        scanf("%d", &choice);

        switch (choice) {
            case 1:
                // 添加新联系人
                printf("很好,让我们创建一个新的联系人:\n");
                printf("输入联系人的姓名:\n");
                scanf("%s", name);
                printf("现在输入电话号码:\n");
                scanf("%s", number);
                addContact(name, number);
                break;
            case 2:
                // 查看电话簿
                printf("这是您的电话簿:\n");
                viewContacts();
                break;
            case 3:
                // 删除联系人
                printf("输入要删除的联系人的姓名:\n");
                scanf("%s", name);
                deleteContact(name);
                break;
        }
    } while (choice != 4); // 循环直到用户选择“退出”

    return 0;
}

// 向电话簿添加联系人的函数
void addContact(char name[], char number[]) {
    FILE *pFile;
    pFile = fopen("Phonebook.txt", "a");
    if (pFile == NULL) {
        printf("打开电话簿时出错。");
        return;
    }
    fprintf(pFile, "姓名: %s \t 电话: %s\n", name, number);
    printf("联系人已创建!\n");
    fclose(pFile);
}

// 查看电话簿中所有联系人的函数
void viewContacts() {
    char fileContent[200];
    FILE *pFile;
    pFile = fopen("Phonebook.txt", "r");

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

    fclose(pFile);
}

// 从电话簿中删除联系人的函数
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("打开文件时出错。");
        return;
    }

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

    fclose(pFile);
    fclose(pTrash);

    // 将旧的电话簿替换为更新后的版本
    remove("Phonebook.txt");
    rename("Trash.txt", "Phonebook.txt");
    printf("联系人已删除。");
}</code>
Copy after login

Program functions

This program implements three key functions:

  1. Add contact:

    • Allow users to enter name and phone number.
    • Store contacts in a file called Phonebook.txt.
  2. View contact:

    • Read and display all contacts stored in Phonebook.txt.
  3. Delete contact:

    • Delete contacts based on the name entered by the user.
    • Create a temporary file to filter out deleted contacts and then replace the original file.

Key knowledge gained from this exercise

  1. File processing in C language:

    • Use fopen, fclose and file operation functions.
    • Handle errors when a file cannot be opened or accessed.
  2. String processing:

    • Use functions such as strcmp and sscanf for string comparison and parsing.
  3. Basic data management:

    • Store and organize data in simple text files.
    • Replace or update file contents by creating temporary files.

How to test code

  1. Copy the code into a .c file and compile it with a C compiler (e.g. gcc):
<code class="language-bash">gcc -o phonebook phonebook.c</code>
Copy after login
  1. Run the compiled program:
<code class="language-bash">./phonebook</code>
Copy after login
  1. Follow the on-screen instructions to add, view, or delete contacts.
  2. Open Phonebook.txt to verify that the data is stored as expected.

Potential improvements

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

  1. Input verification:

    • Make sure the phone number is valid (i.e. only numeric characters).
    • Prevent duplicate names from appearing in the phone book.
  2. Improved UI:

    • Provide more detailed instructions.
    • Using fgets instead of scanf allows the use of multi-word names.
  3. Enhanced file handling:

    • Encrypt data for security.
    • Use a structured format (such as CSV or JSON).
  4. Advanced features:

    • Implement search function to quickly find contacts.
    • Sort phone book alphabetically.

Summary

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

The above is the detailed content of Practicing C: Building a Simple Phonebook Application. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template