Exercise C: Building a simple phonebook application
One of the best ways to learn C language programming is to practice it. This article will take you step through a project I recently completed: a simple phone book application. This app demonstrates file processing and basic data management in C, allowing you to add, view, and delete contacts.
Detailed code explanation
Here is the complete code:
<code class="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("联系人已删除。"); }</string.h></stdio.h></code>
Project Features
This program implements three core functions:
- Add a contact:
- Allows users to enter their name and phone number.
- Store contact information in a file named
phonebook.txt
.
- View contact:
- Read and display all contact information stored in the
phonebook.txt
file.
- Read and display all contact information stored in the
- Delete a contact:
- Delete the contact based on the name entered by the user.
- Filter out deleted contacts by creating temporary files and replace the original files.
Learning gains
Through this exercise, I consolidated the following C language knowledge:
- File processing: Proficient in using
fopen
,fclose
and other file operation functions, and handle the failure of file opening. - String operation: Use functions such as
strcmp
andsscanf
to compare and parse strings. - Basic Data Management: Learn how to store and manage data in simple text files, and update file content by creating temporary files.
Code Testing
- Copy the code into a
.c
file (e.g.phonebook.c
) and compile with a C compiler (e.g. GCC):
<code class="bash">gcc -o phonebook phonebook.c</code>
- Run the compiled program:
<code class="bash">./phonebook</code>
- Follow the on-screen prompts to add, view, or delete contacts.
- Open the
phonebook.txt
file to verify that the data is stored correctly.
Future improvements
This program is a good start and the following improvements can be considered in the future:
- Enter Verification: Verify the validity of the phone number (for example, including only numbers) to prevent duplicate names.
- User interface improvement: Provides clearer prompts, allowing input of names containing multiple words (using
fgets
instead ofscanf
). - Enhanced file processing: Consider data encryption for improved security, using more structured file formats such as CSV or JSON.
- Advanced Features: Add search function to sort contacts alphabetically.
Summarize
This exercise helped me understand the C language file processing and basic data management in the basics. This is a simple but practical program that can serve as the basis for more complex projects. If you are a beginner in C language, you highly recommend giving it a try! This is an interesting and rewarding learning process.
The above is the detailed content of Exercise C: Building a simple phonebook application. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











DMA in C refers to DirectMemoryAccess, a direct memory access technology, allowing hardware devices to directly transmit data to memory without CPU intervention. 1) DMA operation is highly dependent on hardware devices and drivers, and the implementation method varies from system to system. 2) Direct access to memory may bring security risks, and the correctness and security of the code must be ensured. 3) DMA can improve performance, but improper use may lead to degradation of system performance. Through practice and learning, we can master the skills of using DMA and maximize its effectiveness in scenarios such as high-speed data transmission and real-time signal processing.

Using the chrono library in C can allow you to control time and time intervals more accurately. Let's explore the charm of this library. C's chrono library is part of the standard library, which provides a modern way to deal with time and time intervals. For programmers who have suffered from time.h and ctime, chrono is undoubtedly a boon. It not only improves the readability and maintainability of the code, but also provides higher accuracy and flexibility. Let's start with the basics. The chrono library mainly includes the following key components: std::chrono::system_clock: represents the system clock, used to obtain the current time. std::chron

Efficient methods for batch inserting data in MySQL include: 1. Using INSERTINTO...VALUES syntax, 2. Using LOADDATAINFILE command, 3. Using transaction processing, 4. Adjust batch size, 5. Disable indexing, 6. Using INSERTIGNORE or INSERT...ONDUPLICATEKEYUPDATE, these methods can significantly improve database operation efficiency.

Measuring thread performance in C can use the timing tools, performance analysis tools, and custom timers in the standard library. 1. Use the library to measure execution time. 2. Use gprof for performance analysis. The steps include adding the -pg option during compilation, running the program to generate a gmon.out file, and generating a performance report. 3. Use Valgrind's Callgrind module to perform more detailed analysis. The steps include running the program to generate the callgrind.out file and viewing the results using kcachegrind. 4. Custom timers can flexibly measure the execution time of a specific code segment. These methods help to fully understand thread performance and optimize code.

ABI compatibility in C refers to whether binary code generated by different compilers or versions can be compatible without recompilation. 1. Function calling conventions, 2. Name modification, 3. Virtual function table layout, 4. Structure and class layout are the main aspects involved.

Handling high DPI display in C can be achieved through the following steps: 1) Understand DPI and scaling, use the operating system API to obtain DPI information and adjust the graphics output; 2) Handle cross-platform compatibility, use cross-platform graphics libraries such as SDL or Qt; 3) Perform performance optimization, improve performance through cache, hardware acceleration, and dynamic adjustment of the details level; 4) Solve common problems, such as blurred text and interface elements are too small, and solve by correctly applying DPI scaling.

C performs well in real-time operating system (RTOS) programming, providing efficient execution efficiency and precise time management. 1) C Meet the needs of RTOS through direct operation of hardware resources and efficient memory management. 2) Using object-oriented features, C can design a flexible task scheduling system. 3) C supports efficient interrupt processing, but dynamic memory allocation and exception processing must be avoided to ensure real-time. 4) Template programming and inline functions help in performance optimization. 5) In practical applications, C can be used to implement an efficient logging system.

MySQL functions can be used for data processing and calculation. 1. Basic usage includes string processing, date calculation and mathematical operations. 2. Advanced usage involves combining multiple functions to implement complex operations. 3. Performance optimization requires avoiding the use of functions in the WHERE clause and using GROUPBY and temporary tables.
