写一个c语言通讯录管理系统,要求有录入联系人,查询联系人,删除联系人,修改联系人,保存和读取的功能
时间: 2023-11-08 20:03:54 浏览: 66
下面是一个C语言通讯录管理系统的示例代码,包括录入联系人、查询联系人、删除联系人、修改联系人、保存和读取的功能:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_CONTACTS 1000
#define NAME_LENGTH 20
#define PHONE_LENGTH 20
struct Contact {
char name[NAME_LENGTH];
char phone[PHONE_LENGTH];
};
struct Contact contacts[MAX_CONTACTS];
int num_contacts = 0;
void add_contact() {
if (num_contacts == MAX_CONTACTS) {
printf("Error: contact list is full\n");
return;
}
struct Contact new_contact;
printf("Enter name: ");
scanf("%s", new_contact.name);
printf("Enter phone number: ");
scanf("%s", new_contact.phone);
contacts[num_contacts] = new_contact;
num_contacts++;
printf("Contact added successfully\n");
}
void delete_contact() {
char name[NAME_LENGTH];
printf("Enter name: ");
scanf("%s", name);
int i;
for (i = 0; i < num_contacts; i++) {
if (strcmp(contacts[i].name, name) == 0) {
int j;
for (j = i; j < num_contacts - 1; j++) {
contacts[j] = contacts[j + 1];
}
num_contacts--;
printf("Contact deleted successfully\n");
return;
}
}
printf("Contact not found\n");
}
void list_contacts() {
int i;
for (i = 0; i < num_contacts; i++) {
printf("%s: %s\n", contacts[i].name, contacts[i].phone);
}
}
void modify_contact() {
char name[NAME_LENGTH];
printf("Enter name: ");
scanf("%s", name);
int i;
for (i = 0; i < num_contacts; i++) {
if (strcmp(contacts[i].name, name) == 0) {
printf("Enter new phone number: ");
scanf("%s", contacts[i].phone);
printf("Contact modified successfully\n");
return;
}
}
printf("Contact not found\n");
}
void save_contacts() {
FILE* fp = fopen("contacts.txt", "w");
if (fp == NULL) {
printf("Error: could not open file\n");
return;
}
int i;
for (i = 0; i < num_contacts; i++) {
fprintf(fp, "%s %s\n", contacts[i].name, contacts[i].phone);
}
fclose(fp);
printf("Contacts saved successfully\n");
}
void load_contacts() {
FILE* fp = fopen("contacts.txt", "r");
if (fp == NULL) {
printf("Error: could not open file\n");
return;
}
num_contacts = 0;
char name[NAME_LENGTH];
char phone[PHONE_LENGTH];
while (fscanf(fp, "%s %s", name, phone) == 2) {
struct Contact new_contact;
strcpy(new_contact.name, name);
strcpy(new_contact.phone, phone);
contacts[num_contacts] = new_contact;
num_contacts++;
}
fclose(fp);
printf("Contacts loaded successfully\n");
}
int main() {
int choice;
while (1) {
printf("Enter 1 to add contact, 2 to delete contact, 3 to list contacts, 4 to modify contact, 5 to save contacts, 6 to load contacts, or 7 to quit: ");
scanf("%d", &choice);
switch (choice) {
case 1:
add_contact();
break;
case 2:
delete_contact();
break;
case 3:
list_contacts();
break;
case 4:
modify_contact();
break;
case 5:
save_contacts();
break;
case 6:
load_contacts();
break;
case 7:
printf("Quitting\n");
exit(0);
default:
printf("Invalid choice\n");
}
}
return 0;
}
```
该程序使用结构体实现通讯录条目,并使用一个数组来存储所有条目。程序提供了添加、删除、修改、列出、保存和读取通讯录条目的功能,将通讯录保存到名为“contacts.txt”的文件中。
阅读全文