用C语言完成带有文件操作的通讯录管理系统的设计与实现的完整代码
时间: 2023-08-30 13:12:19 浏览: 98
[方案]C语言通讯录管理系统源代码.doc
很抱歉,我并不能提供完整的代码,但我可以给你提供一个基本的框架,你可以根据自己的需求进行修改和完善。
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NAME_LEN 20
#define MAX_PHONE_LEN 11
#define MAX_EMAIL_LEN 30
#define MAX_CONTACTS 1000
typedef struct {
char name[MAX_NAME_LEN];
char phone[MAX_PHONE_LEN];
char email[MAX_EMAIL_LEN];
} Contact;
Contact contacts[MAX_CONTACTS];
int num_contacts = 0;
void load_contacts(char *filename) {
FILE *fp = fopen(filename, "r");
if (fp == NULL) {
printf("Error: Cannot open file '%s'!\n", filename);
return;
}
while (!feof(fp)) {
fscanf(fp, "%s %s %s", contacts[num_contacts].name, contacts[num_contacts].phone, contacts[num_contacts].email);
num_contacts++;
}
fclose(fp);
}
void save_contacts(char *filename) {
FILE *fp = fopen(filename, "w");
if (fp == NULL) {
printf("Error: Cannot open file '%s'!\n", filename);
return;
}
for (int i = 0; i < num_contacts; i++) {
fprintf(fp, "%s %s %s\n", contacts[i].name, contacts[i].phone, contacts[i].email);
}
fclose(fp);
}
void list_contacts() {
printf("Name\t\tPhone\t\tEmail\n");
for (int i = 0; i < num_contacts; i++) {
printf("%-20s%-15s%-30s\n", contacts[i].name, contacts[i].phone, contacts[i].email);
}
}
void add_contact() {
if (num_contacts == MAX_CONTACTS) {
printf("Error: The contacts list is full!\n");
return;
}
printf("Enter name: ");
scanf("%s", contacts[num_contacts].name);
printf("Enter phone: ");
scanf("%s", contacts[num_contacts].phone);
printf("Enter email: ");
scanf("%s", contacts[num_contacts].email);
num_contacts++;
}
void search_contact(char *name) {
for (int i = 0; i < num_contacts; i++) {
if (strcmp(contacts[i].name, name) == 0) {
printf("Name\t\tPhone\t\tEmail\n");
printf("%-20s%-15s%-30s\n", contacts[i].name, contacts[i].phone, contacts[i].email);
return;
}
}
printf("Error: Cannot find contact '%s'!\n", name);
}
void delete_contact(char *name) {
for (int i = 0; i < num_contacts; i++) {
if (strcmp(contacts[i].name, name) == 0) {
for (int j = i; j < num_contacts - 1; j++) {
contacts[j] = contacts[j + 1];
}
num_contacts--;
printf("Contact '%s' has been deleted!\n", name);
return;
}
}
printf("Error: Cannot find contact '%s'!\n", name);
}
int main() {
char filename[] = "contacts.txt";
load_contacts(filename);
int choice;
char name[MAX_NAME_LEN];
while (1) {
printf("1. List contacts\n");
printf("2. Add contact\n");
printf("3. Search contact\n");
printf("4. Delete contact\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
list_contacts();
break;
case 2:
add_contact();
break;
case 3:
printf("Enter name: ");
scanf("%s", name);
search_contact(name);
break;
case 4:
printf("Enter name: ");
scanf("%s", name);
delete_contact(name);
break;
case 5:
save_contacts(filename);
exit(0);
default:
printf("Error: Invalid choice!\n");
break;
}
}
return 0;
}
```
这个通讯录管理系统包括加载和保存通讯录文件、列出联系人、添加联系人、搜索联系人和删除联系人等功能。你可以根据需要对其进行修改和完善。
阅读全文